Google Maps API-检索2个坐标之间的道路距离 [英] Google Maps API - Retrieve the road distance between 2 coordinates

查看:62
本文介绍了Google Maps API-检索2个坐标之间的道路距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望在这里找到一个已经为此工作过的人,可以给我一个如何实现它的例子.

Hope to find here someone that already worked with this and can give me an example of how to accomplish it.

预期结果-在一个简单的HTML页面中,我想要2个使用Google Maps API(Places API?)具有自动完成功能的输入字段,一个输入是开始,另一个输入是结束,它将给我这2个地方的坐标,我要用这2个坐标来计算这2个地方之间的道路距离(以KM为单位),并将结果显示在屏幕上.

Expected Results -In a simple HTML page i want 2 input fields with autocomplete using the Google Maps API (Places API?) one input is the start the other input is the end, and it will give me the coordinates of this 2 places, and with those 2 coordinates i want to calculate the road distance in KM between this 2 places and display the result on the screen.

我做了一些研究,并在这里想出了用于自动完成输入的代码,并带有地点名称:自动完成输入的示例

I did some research and i came up with this code here for the autocomplete inputs with the name of the places: example of autocomplete input

   google.maps.event.addDomListener(window,'load',initialize);
function initialize(){
    var autocomplete =new google.maps.places.Autocomplete(document.getElementById('txtautocomplete'));
    google.maps.events.addListener(autocomplete, 'plac_changed', function (){
        var places= autocomplete.getplace();
        var location= "<b>Location:</b>"+places.formatted_address+"<br/>";
        location += "<b>Latitude:</b>"+places.geometry.location.lat+"<br/>";
        location += "<b>Longitude:</b>"+places.geometry.location.lng    
    });
}

并计算两点之间的道路距离,我在有关路线API的文档中看到了这一点……并且我保存了代码:

and to calculate the road distance between 2 points i saw this in the documentation about the directions API somewhere... and i kept the code :

var startcoords=new google.maps.LatLng(latitude,longitude);
var fromcoords=new google.maps.LatLng(latitude,longitude);


let directionsService = new google.maps.DirectionsService();
  let directionsRenderer = new google.maps.DirectionsRenderer();
  directionsRenderer.setMap(map); // Existing map object displays directions
  // Create route from existing points used for markers
  const route = {
      origin: startcoords,
      destination: fromcoords,
      travelMode: google.maps.TravelMode.DRIVING
  }

  directionsService.route(route,
    function(response, status) { // anonymous function to capture directions
      if (status !== 'OK') {
        window.alert('Directions request failed due to ' + status);
        return;
      } else {
        directionsRenderer.setDirections(response); // Add route to the map
        var directionsData = response.routes[0].legs[0]; // Get data about the mapped route
        if (!directionsData) {
          window.alert('Directions request failed');
          return;
        }
        else {
          document.getElementById('msg').innerHTML += " Driving distance is " + directionsData.distance.text + " (" + directionsData.duration.text + ").";
        }
      }
    });

对此抱歉,我是javascript的新手,我已经在这里呆了几天了.

Sorry for this, im quite new with javascript , i have been stuck here for a few days already..

推荐答案

首先,不建议在Directions API请求中使用latlng坐标,因为它可能会影响起点和终点的位置精度.因此,我建议改用formatted_address.

由于您要将Places API与2个输入字段(开始位置和结束位置输入字段)一起使用,因此需要创建Places API的两个实例.例如:

Since you want to use Places API with 2 input fields, start and end location input fields, you will need to make a two instance of Places API. For example:

var startAutocomplete = new google.maps.places.Autocomplete(startInput);
var endAutocomplete = new google.maps.places.Autocomplete(endInput);

您将需要从 getPlace()方法获取值.在这种情况下,我将 formatted_address 值存储在 startValue endValue 变量中,这些变量稍后将传递给路线服务.开头&的 formatted_address 值.终端位置足以分别用作起源目的地.

You will need to get the values from the getPlace() method. In this case, I stored the formatted_address value in a startValue and endValue variable which later on you will pass to directions service. The formatted_address value of both start & end location is sufficient to serve as the origin and destination respectively.

 var startValue, endValue; 

 startAutocomplete.addListener("place_changed", function() {
     startValue = startAutocomplete.getPlace().formatted_address;
 });

 endAutocomplete.addListener("place_changed", function() {
     endValue = endAutocomplete.getPlace().formatted_address;
 });

对于 DirectionsService ,您可以使用从 getPlace()方法获得的值,如下所示:

For the DirectionsService, you can use the values you got from the getPlace() method like this:

directionsService.route({
   origin: startValue,
   destination: endValue,
   travelMode: "DRIVING"
}

您可以查看我在codeandbox.io上此处制作的示例以获取更好地了解如何在JavaScript上执行此操作.作为奖励,我还添加了 alternativeRoutes 函数,该函数将显示最快和最短的路由.

You can check out the example I made here on codesandbox.io to get a better view on how to do this on JavaScript. As a bonus I also added the alternativeRoutes function which will display the fastest and shortest routes.

注意:您需要在示例上使用自己的API密钥才能工作.

NOTE: you need to use your own API key on the example to work.

这篇关于Google Maps API-检索2个坐标之间的道路距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆