Google Maps API路线服务

时间:2018-11-19 14:02:33

标签: javascript asp.net-mvc google-maps google-maps-api-3

我正在使用Google Maps API方向服务来获取两个航路点之间的距离。我也在使用场所自动完成功能。偶尔我会得到疯狂的结果。例如,当我从相距10英里的地方选择两个地址时,我会得到类似1603英里的结果。如果我重新输入并重新选择该地址,如果自己更正。我的代码如下:

// ********************  The Google API  ********************

var source, destination;
var directionsDisplay;
var directionsService;
if (typeof google === 'object' && typeof google.maps === 'object') {
    directionsService = new google.maps.DirectionsService();

    // set up places autocomplete
    var start = document.getElementById('GoogleFromAddress1');
    var startAutocomplete = new google.maps.places.Autocomplete(start);

    var end = document.getElementById('GoogleToAddress1');
    var endAutocomplete = new google.maps.places.Autocomplete(end);

    // add the places auto complete listener for when the values change
    startAutocomplete.addListener('place_changed', function () {
        var startAddress = $('#GoogleFromAddress1').val();
        var endAddress = $('#GoogleToAddress1').val();
        if (startAddress)
        {
            $('#FromAddress1').val(startAddress);
        }
        GetGoogleDistance();
    });

    endAutocomplete.addListener('place_changed', function () {
        var endAddress = $('#GoogleToAddress1').val();
        if (endAddress)
        {
            $('#ToAddress1').val(endAddress);
        }
        GetGoogleDistance();
    });
}

// use google maps to get the distance
function GetGoogleDistance() {
    var startAddress = $('#FromAddress1').val();
    var endAddress = $('#ToAddress1').val();
    if (typeof google === 'object' && typeof google.maps === 'object') {
        if (startAddress && endAddress) {
            var request = {
                origin: startAddress,
                destination: endAddress,
                provideRouteAlternatives: true,
                travelMode: google.maps.TravelMode.DRIVING
            };
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    var conversionMetersToMiles = 0.000621371192237;

                    var routeIndex = 0;
                    var distanceMeters = response.routes[0].legs[0].distance.value
                    // set the map to also show the shortest route by distance
                    var distance = (distanceMeters * conversionMetersToMiles).toFixed(1);
                    console.log((distanceMeters * conversionMetersToMiles).toFixed(1));
                    $('#CalculatedDistance').val(distance);
                }
            });
        }
    }
}

示例:

enter image description here

明尼苏达州圣保罗市和明尼苏达州奥吉维市之间的距离约为75英里。

还有其他人遇到吗?由于我的应用程序永远不会用于计算我所居住的州以外的里程,因此我想到了只检查距离是否大于500英里并警告用户重试。

1 个答案:

答案 0 :(得分:1)

我建议您在路线请求中使用位置ID代替文本值。用户从自动完成功能中选择地址后,您就可以检索所选的地点ID。这样,您可以确定正在计算用户从自动完成元素中选择的地址之间的路由,因此不会产生错误。

请看以下示例,演示此方法。

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

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer({
    draggable: true
  });
  var mapOptions = {
    zoom:10,
    center: new google.maps.LatLng(32.5101466,-92.0436835) 
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  directionsDisplay.setMap(map);
  
  var inputFrom = document.getElementById('from');
  var autocompleteFrom = new google.maps.places.Autocomplete(inputFrom, {});
  autocompleteFrom.bindTo('bounds', map);
  autocompleteFrom.addListener('place_changed', function() {
      var place = autocompleteFrom.getPlace();
      placeId1 = place.place_id;
  });
  
  var inputTo = document.getElementById('to');
  var autocompleteTo = new google.maps.places.Autocomplete(inputTo, {});
  autocompleteTo.bindTo('bounds', map);
  autocompleteTo.addListener('place_changed', function() {
      var place = autocompleteTo.getPlace();
      placeId2 = place.place_id;
  });
  
}

function calcRoute() {
  if (!placeId1) {
    alert("Please select origin");
    return;
  }
  if (!placeId2) {
    alert("Please select destination");
    return;
  }
  var start = {
     placeId: placeId1
  };
  var end = {
     placeId: placeId2
  };
  var request = {
      origin: start,
      destination:end,
      travelMode: google.maps.TravelMode.DRIVING,
      provideRouteAlternatives: false
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var conversionMetersToMiles = 0.000621371192237;
      var distanceMeters = response.routes[0].legs[0].distance.value
      var distance = (distanceMeters * conversionMetersToMiles).toFixed(1);
      alert("Distance: " + distance + " miles");
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas {
  height: 100%;
  margin: 0px;
  padding: 0px
}
<input type="text" name="from" id="from" placeholder="Select origin" />
<input type="text" name="to" id="to" placeholder="Select destination" />
<input type="button" name="calcroute" value="Get route" onclick="calcRoute();return false;" />
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=quarterly&libraries=places&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU"></script>

我希望这会有所帮助!