1

我正在使用在http://exploregooglemaps.blogspot.com.br/2012/02/measuring-distance-with-markers.html找到的一些有用代码来添加标记和测量距离。

我希望标记在默认情况下捕捉到道路,但是当用户按住 shift 键时,会使用直线。

我已经设法为 shift 键实现了 if 语句,当我按住 shift 键时会绘制一条路径,但是默认情况下不会绘制到道路路径的捕捉。

我正在调用两个函数,一个用于绘制直线drawPath,另一个用于绘制与道路线drawPathD的对齐

任何帮助将非常感激。

<code>
var map,
service = new google.maps.DirectionsService(),
shiftPressed = false,
poly;

var path = [];

shiftPressed = false;
var markers = [];
var routePoints = [];

google.maps.event.addDomListener(document, "keydown", function () {
shiftPressed = true;
});
google.maps.event.addDomListener(document, "keyup", function () {
shiftPressed = false;
});

function $(id) {
return document.getElementById(id);
}

var map;
var mapOptions = {
center: new google.maps.LatLng(-23.5489433, - 46.6388182),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

var markers = [];
var line;

function initialize() {
map = new google.maps.Map($("map_canvas"), mapOptions);
line = new google.maps.Polyline({
map: map,
strokeColor: "#FF3333",
strokeOpacity: 0.5,
strokeWeight: 8
});

google.maps.event.addListener(map, 'click', function (event) {
var marker = new google.maps.Marker({
map: map,
position: event.latLng,
draggable: true
});


if (shiftPressed) {

markers.push(marker);
drawPath();

} else {

markers.push(marker);
drawPathD();

}


google.maps.event.addListener(marker, 'dblclick', function (event) {
marker.setMap(null);
drawPath();
});

google.maps.event.addListener(marker, 'drag', function (event) {
drawPath();
});
});
}

function countMarkers() {
count = 0;
for (var i = routePoints.length - 1; i >= 0; i--) {
if (markers[i].getMap() == null) {
routePoints.splice(i, 1);
} else {
count++;
}
}
return count;
}

function drawPath() {
countMarkers();

var coords = [];
for (var i = 0; i < markers.length; i++) {
coords.push(markers[i].getPosition());
}
line.setPath(coords);

meters = google.maps.geometry.spherical.computeLength(coords);
$("distKm").value = Math.round(meters / 1000 * 100) / 100;
$("distMi").value = Math.round(meters / 1609 * 100) / 100;
}

function drawPathD(event) {
countMarkers();
var coords = [];

service.route({
origin: path[path.length - 1],
destination: event.latLng,
travelMode: google.maps.DirectionsTravelMode.WALKING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
path = path.concat(result.routes[0].overview_path);
routePoints.setPath(path);
}
});



meters = google.maps.geometry.spherical.computeLength(coords);
$("distKm").value = Math.round(meters / 1000 * 100) / 100;
$("distMi").value = Math.round(meters / 1609 * 100) / 100;
}

function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null)
}
drawPath();
}
google.maps.event.addDomListener(window, 'load', initialize);

</code>
4

1 回答 1

0

以下是如何在 Google Maps API v3 中实现“对齐道路”功能: polyline snap to road using google maps api v3

于 2012-09-09T22:40:06.570 回答