我想当我点击地图时,标记会自动贴到最近的街道上。这里有一个很好的例子:http://econym.org.uk/gmap/example_snappath.htm(主页:http://econym.org.uk/gmap/snap.htm),但是这个例子是针对Google Maps版本2的。在版本3中有没有实现这个功能的方法?
我想当我点击地图时,标记会自动贴到最近的街道上。这里有一个很好的例子:http://econym.org.uk/gmap/example_snappath.htm(主页:http://econym.org.uk/gmap/snap.htm),但是这个例子是针对Google Maps版本2的。在版本3中有没有实现这个功能的方法?
您提供的示例是通过进行方向查找,然后从中获取第一个位置来获得结果的。在API v3中,可以使用以下代码实现此操作,其中“map”是您地图的名称:
var directionsService = new google.maps.DirectionsService();
google.maps.event.addListener(map, 'click', function(event) {
var request = {
origin:event.latLng,
destination:event.latLng,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var marker = new google.maps.Marker({
position: response.routes[0].legs[0].start_location,
map: map,
title:"Hello World!"
});
}
});
});
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=YOU API KEY&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var myOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var directionsService = new google.maps.DirectionsService();
google.maps.event.addListener(map, 'click', function(event) {
var request = {
origin:event.latLng,
destination:event.latLng,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var marker = new google.maps.Marker({
position: response.routes[0].legs[0].start_location,
map: map,
title:"Hello World!"
});
}
});
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>