How to find nearest location using latitude and longitude from a json data

前端 未结 3 1215
无人共我
无人共我 2021-02-06 15:19

I\'m trying to make a website that ask for user\'s location then find the closest location (100m radius) from it\'s position using GeoLocation and display the result in HTML.

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-06 15:55

    get current user's location using HTML5 geolocation and find nearest location within 100 meters.

    include and use below google maps libs


    Snippet

    //calculates distance between two points in km's
    function calcDistance(p1, p2) {
      return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
    }
    
    function getPosition(position) {
      var userPosition = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
    
      $.getJSON("places.json", function(data) {
        for (var i = 0; i < data.length; i++) {
    
          var p1 = new google.maps.LatLng(userPosition.lat, userPosition.lng);
          var p2 = new google.maps.LatLng(data[i].lat, data[i].lng);
    
          var distance = calcDistance(p1, p2) * 1000;
    
          if ((distance * 1000) <= 100) {
            html += '

    ' + data[i].location + ' - ' + data[i].code + '

    '; $('#nearbystops').append(html); } } }) } // get user's current latitude & longitude function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(getPosition); } else { alert("Geolocation is not supported by this browser."); } } getLocation();

提交回复
热议问题