无法获取 gmaps 地理编码数据

Cannot get gmaps geocoding data

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

<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'。我尝试按照 google 代码片段建议进行制作,如下所示:'Copenhagen,+Denmark'(空 space 被替换为 +),但仍然无法正常工作。

问题:

  1. 你不能return来自异步回调函数的任何东西,你需要使用回调函数中的数据。
  2. 您在地理编码结果返回之前提交表单(return onsubmit 函数中的 false,然后在所有回调处理完成后提交表单。
  3. 您正在计算直线距离 (computeDistanceBetween) 并将其与行驶距离进行比较。

proof of concept fiddle

代码片段:

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);
html,
body,
#map_canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
<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>