Use google maps computeDistanceBetween to get the closest location returns NaN

匿名 (未验证) 提交于 2019-12-03 02:01:02

问题:

Ok so I have set up a map and an autocomplete field on a testing site.

My goal is to get the user to input his/her address into the field and then when he/she clicks confirm work out the closest store to them based on the information provided.

I have the lat/long for each store and with the help of autocomplete I now have the lat/long of the users address but when I use the computeDistanceBetween method provided in the documentation I get NaN instead of a desired result.

Here is a link to the test site to get an idea - http://dev.touch-akl.com/map/

And Below is what I have tried so far

    //----------------------------------------------------------------     //--- Search Box -------------------------------------------------      var input = document.getElementById('address');     var $confirm = $('#confirm');      var options = {        types: ['geocode'],        componentRestrictions: {country: 'nz'}//Turkey only     };              var autocomplete = new google.maps.places.Autocomplete(input,options);     autocomplete.bindTo('bounds', map);      $confirm.click(function(){          var _street = $('#address').val();         var place = autocomplete.getPlace();         var _coordinates = place.geometry.location.toString();         var _delivery = _coordinates.substring(1, _coordinates.length - 1);         var _kCord = '-36.874694,174.735292';         var _pCord = '-36.858317,174.782284'          console.log(_coordinates);         console.log(_delivery);          console.log(google.maps.geometry.spherical.computeDistanceBetween(_pCord, _delivery));         console.log(google.maps.geometry.spherical.computeDistanceBetween(_kCord, _delivery));       });

回答1:

google.maps.geometry.spherical.computeDistanceBetween requires that you feed it two google.maps.LatLng objects whereas you are using strings, and that won't work. The following should...

$confirm.click(function(){     var _street = $('#address').val();     var place = autocomplete.getPlace();     var _coordinates = place.geometry.location; //a google.maps.LatLng object     var _kCord = new google.maps.LatLng(-36.874694, 174.735292);     var _pCord = new google.maps.LatLng(-36.858317, 174.782284);      console.log(_coordinates);      console.log(google.maps.geometry.spherical.computeDistanceBetween(_pCord, _coordinates));     console.log(google.maps.geometry.spherical.computeDistanceBetween(_kCord, _coordinates)); });


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