更新时间:2023-12-05 19:30:10
米尔侯赛因沙基尔的回答实际上是正确的。我一直在寻找一个答案,他给了它。他的格式和解释是可怕的,但。以下是我已经做到了(完全code):
Mir Shakeel Hussain's answer is actually correct. I was looking for an answer and he gave it. His formatting and explanation is awful though. Here's how I've done it (complete code):
var map;
var poly; //the line
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 52.092876, lng: 5.104480},
zoom: 8
});
}
$(document).ready(function () {
$('#addLines').click(toggleLinesButton);
$('#undoLine').click(undoPolyline);
});
var mayDrawLines = false;
function toggleLinesButton (el) {
if (mayDrawLines) {
mayDrawLines = false;
$('#addLines').removeClass('active');
removePoly();
} else {
mayDrawLines = true;
$('#addLines').addClass('active');
createPoly();
}
}
var polyLineListener = null;
function createPoly () {
if (!poly) {
poly = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
});
poly.setMap(map);
}
// Add a listener for the click event
polyLineListener = google.maps.event.addListener(map, 'click', addLatLng);
}
function removePoly () {
google.maps.event.removeListener(polyLineListener);
//poly = null;
polyLineListener = null;
}
var polyIndex = 0;
//Mirrors the path array to find index to delete and such
var mirrorCoordinates = [];
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event) {
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
path.push(event.latLng);
mirrorCoordinates.push(event.latLng);
polyIndex++;
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map,
visible: false
});
}
function undoPolyline() {
mirrorCoordinates.pop();
polyIndex--;
poly.getPath().setAt(polyIndex, mirrorCoordinates[mirrorCoordinates.length - 1]);
poly.getPath().removeAt(polyIndex);
}