【问题标题】:Google Maps API V3: pass marker coordinate to google directions service requestGoogle Maps API V3:将标记坐标传递给谷歌方向服务请求
【发布时间】:2012-11-17 00:06:11
【问题描述】:

用户使用 Google Places API 搜索我的地图,该 API 会向我的地图添加标记。我在每个标记信息窗口内都有一个单击事件,以获取到该标记的方向。 如何将所选标记的坐标传递给我的 google 路线服务请求?

到目前为止,我将var placeLoc = null; 声明为全局变量。我在创建标记函数中定义了placeLoc=place.geometry.location;。然后我有:

function calcRoute() {
 var start = myLatLng;
 var end = placeLoc;
 var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.DirectionsTravelMode.BICYCLING
 };
 directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
    }
 });
}

该函数将方向呈现给错误的标记。我猜它只是为搜索后返回的数组中的第一个标记提供方向,而不是我选择的实际标记。如何提供路线请求选择标记的坐标?

下面是将搜索结果放入place变量的代码:

 google.maps.event.addListener(searchBox, 'places_changed', function() {
     var places = searchBox.getPlaces();
     // alert("getPlaces returns "+places.length+" places");

    for (var i = 0; i < gmarkers.length; i++) {
         gmarkers[i].setMap(null);
    }

    gmarkers = [];
    var bounds = new google.maps.LatLngBounds();

    for (var i = 0, place; place = places[i]; i++) {
       var place = places[i];
       createMarker(place);
       bounds.extend(place.geometry.location);
    }
    map.fitBounds(bounds);
    // if (markers.length == 1) map.setZoom(17);
 });

【问题讨论】:

    标签: google-maps-api-3 driving-directions


    【解决方案1】:

    这样的?

    function createMarker(options) {
      var marker = new google.maps.Marker(options);
    
      google.maps.event.addListener(marker, 'click', function() {
        placeLoc = marker.getPosition();
        calcRoute();
      });
    
      return marker;
    }
    

    【讨论】:

    • 我试过了,但它没有给我指向我选择的标记的方向。它仍然将方向返回到数组中的另一个标记。但我确实认为 marker.getPosition() 是我在代码中缺少的地方。我只需要弄清楚在哪里,
    • 我找到了这个例子:econym.org.uk/gmap/example_map4c.htm 我相信通过这个代码传递标记位置 '&lt;input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + '"/&gt;'; 这个代码使用谷歌地图 api v2。类似的东西会在 V3 中起作用还是我应该寻找的 getPosition() 函数?
    • 终于想通了。这与您的答案相似,关键是将 marker.getPosition 放入具有打开信息窗口的事件侦听器的函数中。我认为就您的功能代码而言,它应该足以帮助人们解决这个问题。谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-02-04
    • 2012-07-15
    • 2014-05-20
    • 2012-06-09
    • 1970-01-01
    • 2012-05-11
    • 2011-09-05
    • 2016-11-06
    相关资源
    最近更新 更多