无法获取gmaps地理编码数据

时间:2015-08-23 16:00:08

标签: javascript google-maps google-geocoding-api

我在表单中有一个隐藏字段:

<form> 
     <input id="distance" name="km" type="hidden">
</form>

我只想用这个字段填充用户选择的2个地址之间的距离。然后我只需使用表单提交它,然后用它来处理服务器。我在这里调用calculateDistance func:

$('#my_form_id').on("submit", function (e) {
    calculateDistance();
    // other stuff
    return true;
});

这就是我试图找到距离的方式:

function calculateDistance() {
    var startPoint = $('#main_from_route_input').val();
    var endPoint = $('#main_to_route_input').val();
    var geocoderStart = new google.maps.Geocoder();
    var geocoderEnd = new google.maps.Geocoder();
    var coordsStart, coordsEnd;

geocoderStart.geocode({'address': startPoint}, function (response, status) {
    if(status != google.maps.GeocoderStatus.OK){
        alert('Geocode of first address failed: ' + status);
    }
    coordsStart = response[0].geometry.location;

    geocoderEnd.geocode({'address': endPoint}, function (response, status) {
        if(status != google.maps.GeocoderStatus.OK){
            alert('Geocode of second address failed: ' + status);
        }
        coordsEnd = response[0].geometry.location;
        var distance = (google.maps.geometry.spherical.computeDistanceBetween(coordsStart, coordsEnd) / 1000).toFixed(2);
        $('#distance').val(distance);
    });
});
}

我提出了上层解决方案。但我甚至没有进入回调函数。当我调试并进入回调时,它就被跳过了。代码似乎是正确的(与其他答案相同)。问题在哪里?

我收到的地址值为'Copenhagen, Denmark''Berlin, Germany'。我尝试将其设置为谷歌代码snipet建议,如下所示:'Copenhagen,+Denmark'(空格替换为+),但仍无效。

1 个答案:

答案 0 :(得分:1)

的问题:

  1. 您无法从异步回调函数返回任何内容,您需要使用回调函数中的数据。
  2. 您在地理编码结果返回之前提交表单(在onsubmit函数中返回false,然后在完成所有回调处理后提交表单。
  3. 您正在计算直线距离(computeDistanceBetween)并将其与行驶距离进行比较。
  4. proof of concept fiddle

    代码段

    &#13;
    &#13;
    var geocoder;
    var map;
    
    function initialize() {
      map = new google.maps.Map(
        document.getElementById("map_canvas"), {
          center: new google.maps.LatLng(37.4419, -122.1419),
          zoom: 13,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
      calculateDistance();
    }
    
    function calculateDistance() {
      var bounds = new google.maps.LatLngBounds();
      var path = [];
      var startPoint = $('#main_from_route_input').val();
      var endPoint = $('#main_to_route_input').val();
      var geocoderStart = new google.maps.Geocoder();
      var geocoderEnd = new google.maps.Geocoder();
      var coordsStart, coordsEnd;
    
      geocoderStart.geocode({
        'address': startPoint
      }, function(response, status) {
        if (status != google.maps.GeocoderStatus.OK) {
          alert('Geocode of first address failed: ' + status);
        }
        coordsStart = response[0].geometry.location;
        bounds.extend(coordsStart);
        var startMark = new google.maps.Marker({
          position: coordsStart,
          map: map,
          title: "start"
        });
        path.push(coordsStart);
        geocoderEnd.geocode({
          'address': endPoint
        }, function(response, status) {
          if (status != google.maps.GeocoderStatus.OK) {
            alert('Geocode of second address failed: ' + status);
          }
          coordsEnd = response[0].geometry.location;
          bounds.extend(coordsEnd);
          var endMark = new google.maps.Marker({
            position: coordsEnd,
            map: map,
            title: "end"
          });
          path.push(coordsEnd);
          var polyline = new google.maps.Polyline({
            path: path,
            map: map
          });
          var distance = (google.maps.geometry.spherical.computeDistanceBetween(coordsStart, coordsEnd) / 1000).toFixed(2);
          $('#distance').val(distance);
          map.fitBounds(bounds);
        });
      });
    }
    
    google.maps.event.addDomListener(window, "load", initialize);
    &#13;
    html,
    body,
    #map_canvas {
      height: 500px;
      width: 500px;
      margin: 0px;
      padding: 0px
    }
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
    <form>
      <input id="distance" name="km">
      <input id="main_from_route_input" value="Copenhagen, Denmark" />
      <input id="main_to_route_input" value="Berlin, Germany" />
    </form>
    <div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
    &#13;
    &#13;
    &#13;