Cannot get gmaps geocoding data

旧时模样 提交于 2019-11-29 18:18:35

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