谷歌地图v3:创建两点之间的路线

6

我正在使用Google Maps API开发一个Web应用程序。 我试图在两个点之间创建路径,但出于某种原因,我还没有弄清如何创建它。以下是我的代码,请告诉我是否有我漏掉的内容。谢谢。

<script>
var Center=new google.maps.LatLng(18.210885,-67.140884);
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
var properties = {
    center:Center,
    zoom:20,
    mapTypeId:google.maps.MapTypeId.SATELLITE
};

map=new google.maps.Map(document.getElementById("map"), properties);
directionsDisplay.setMap(map);

var marker=new google.maps.Marker({
position:Center,
animation:google.maps.Animation.BOUNCE,
});

marker.setMap(map);

}

function Route() {

var start = new google.maps.LatLng(18.210885,-67.140884);
var end =new google.maps.latLng(18.211685,-67.141684);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.WALKING
 };
 directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
  directionsDisplay.setDirections(result);
}
});
} 

google.maps.event.addDomListener(window,'load',initialize);
</script>

2
你在哪里调用函数Route()?我在你的代码中没有看到它被调用的地方。 - Marcelo
1个回答

15

如果我这样做,它对我有效:

  1. call the Route function
  2. change:

    var end =new google.maps.latLng(18.211685,-67.141684);
    

to:

    var end =new google.maps.LatLng(18.211685,-67.141684);

JavaScript是大小写敏感的,浏览器会在JavaScript控制台中报告错误。

正常工作版本

代码片段:

var Center = new google.maps.LatLng(18.210885, -67.140884);
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var properties = {
    center: Center,
    zoom: 20,
    mapTypeId: google.maps.MapTypeId.SATELLITE
  };

  map = new google.maps.Map(document.getElementById("map"), properties);
  directionsDisplay.setMap(map);

  var marker = new google.maps.Marker({
    position: Center,
    animation: google.maps.Animation.BOUNCE,
  });

  marker.setMap(map);
  Route();
}

function Route() {

  var start = new google.maps.LatLng(18.210885, -67.140884);
  var end = new google.maps.LatLng(18.211685, -67.141684);
  var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.TravelMode.WALKING
  };
  directionsService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(result);
    } else {
      alert("couldn't get directions:" + status);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
  margin: 0;
  padding: 0;
  height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map"></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接