Cannot get gmaps geocoding data

杀马特。学长 韩版系。学妹 提交于 2019-11-28 12:57:09

问题


I have a hidden field inside a form:

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

And I just want to populate this field with the distance between 2 addresses, chosen by the user. Then I simply submit it with the form and do the server stuff with it. Here I call the calculateDistance func:

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

This is how I'm trying to get the distance:

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);
    });
});
}

I came up with the upper solution. But I don't even get into the callback functions. When I debug and get to the callback, it is just skipped. The code seems to be correct (the same as in other answers). Where is the problem?

I receive the addresses values as 'Copenhagen, Denmark' and 'Berlin, Germany', for example. I tried making it as in google code snipet suggestions, as follows: 'Copenhagen,+Denmark' (empty space is replaced with a +), but doesn't work still.


回答1:


Issues:

  1. you can't return anything from an asynchronous callback function, you need to use the data inside the callback function.
  2. you are submitting the form before the geocoded results have come back (return false in the onsubmit function, then submit the form once all the callback processing has completed.
  3. You are calculating the straight line distance (computeDistanceBetween) and comparing that to the driving distance.

proof of concept fiddle

code snippet:

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>


来源:https://stackoverflow.com/questions/32168626/cannot-get-gmaps-geocoding-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!