简体   繁体   English

Google Maps API:将路线服务与watchPosition地理位置结合在一起

[英]Google Maps API: Combining Directions Service with watchPosition Geolocation

I'm trying to display a map using Google's directions service with an origin, destination, and the blue directions line connecting the two. 我正在尝试使用Google的路线服务显示地图,其中包含起点,目的地和连接这两者的蓝色路线。 However, I am trying to use watchPosition for the origin lat/lng. 但是,我正在尝试将watchPosition用于原始纬度/经度。

So far everything displays correctly, except the green origin marker doesn't move as watchPosition updates with new lat/lng coordinates. 到目前为止,一切都可以正确显示,但绿色的原点标记不会随着watchPosition用新的经/纬度坐标更新而移动。 Is what I'm trying to do possible? 我想做的事可能吗? Or would I just have to create a third marker that follows the user's coordinates? 还是只需要创建跟随用户坐标的第三个标记?

Here is what I have in my script: 这是我的脚本中的内容:

    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;

    function initialize() {
      directionsDisplay = new google.maps.DirectionsRenderer();
      var mapOptions = {
        zoom:7,
        center: new google.maps.LatLng(38.5815719, -121.4943996)
      }
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      directionsDisplay.setMap(map);
      calcRoute();
}

function handleNoGeolocation(errorFlag) {
  if (errorFlag) {
    var content = 'Error: The Geolocation service failed.';
} else {
    var content = 'Error: Your browser doesn\'t support geolocation.';
}

  var options = {
    map: map,
    position: new google.maps.LatLng(<%= @order.origin_lat %>, <%= @order.origin_lng %>),
    content: content
  };

  var infowindow = new google.maps.InfoWindow(options);
  map.setCenter(options.position);
}



function calcRoute() {
    if(navigator.geolocation) {
        navigator.geolocation.watchPosition(function(position) {
            var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            var request = {
                  origin: pos,
                  destination: new google.maps.LatLng(<%= @order.user.latitude %>, <%= @order.user.longitude %>),
                  travelMode: google.maps.TravelMode.DRIVING
              };
            directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                  directionsDisplay.setDirections(response);
                }
            });
        },

        function() {
        handleNoGeolocation(true);
        });
    } else {
    // Browser doesn't support Geolocation
        handleNoGeolocation(false);
    }

}

google.maps.event.addDomListener(window, 'load', initialize);

看起来这在移动网络中不容易实现,因此我刚刚创建了第三个标记,该标记根据用户的位置移动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM