Javascript查找经纬度和半径的位置

Posted

技术标签:

【中文标题】Javascript查找经纬度和半径的位置【英文标题】:Javascript find location with lat,long and radius 【发布时间】:2020-08-01 18:32:37 【问题描述】:

我需要找到所提供的经纬度和半径附近的所有位置。我想我可以通过使用地理围栏来实现这一点,但我不知道如何进行。我有以下数据。 设置 lat long 并获取每个 lat long 在5km 内的半径位置。

任何人帮助如何开始这个。

我的输入:

经纬度

33.450909, -112.073196
33.466210, -112.064620
33.451640,  -112.099130
33.437160,  -112.048400
33.480860,  -112.082130
33.489950,  -112.074700

目前尝试过:

<!DOCTYPE html >
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <title>Creating a Store Locator on Google Maps</title>
  <style>
    /* Always set the map height explicitly to define the size of the div
     * element that contains the map. */
    #map 
      height: 100%;
    
    /* Optional: Makes the sample page fill the window. */
    html, body 
      height: 100%;
      margin: 0;
      padding: 0;
    
 </style>
  </head>
  <body style="margin:0px; padding:0px;" onload="initMap()">
    <div>
         <label for="raddressInput">Search location:</label>
         <input type="text" id="addressInput" size="15"/>
        <label for="radiusSelect">Radius:</label>
        <select id="radiusSelect" label="Radius">
          <option value="50" selected>50 kms</option>
          <option value="30">30 kms</option>
          <option value="20">20 kms</option>
          <option value="10">10 kms</option>
        </select>

        <input type="button" id="searchButton" value="Search"/>
    </div>
    <div><select id="locationSelect" style="width: 10%; visibility: hidden"></select></div>
    <div id="map" style="width: 100%; height: 90%"></div>
    <script>
      var map;
      var markers = [];
      var infoWindow;
      var locationSelect;

        function initMap()  
          var sydney = lat: 33.450909, lng: -112.073196;
          map = new google.maps.Map(document.getElementById('map'), 
            center: sydney,
            zoom: 11,
            mapTypeId: 'roadmap',
            mapTypeControlOptions: style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
          );
          infoWindow = new google.maps.InfoWindow();

          searchButton = document.getElementById("searchButton").onclick = searchLocations;

          locationSelect = document.getElementById("locationSelect");
          locationSelect.onchange = function() 
            var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
            if (markerNum != "none")
              google.maps.event.trigger(markers[markerNum], 'click');
            
          ;
        

       function searchLocations() 
         var address = document.getElementById("addressInput").value;
         var geocoder = new google.maps.Geocoder();
         geocoder.geocode(address: address, function(results, status) 
           if (status == google.maps.GeocoderStatus.OK) 
            searchLocationsNear(results[0].geometry.location);
            else 
             alert(address + ' not found');
           
         );
       

       function clearLocations() 
         infoWindow.close();
         for (var i = 0; i < markers.length; i++) 
           markers[i].setMap(null);
         
         markers.length = 0;

         locationSelect.innerHTML = "";
         var option = document.createElement("option");
         option.value = "none";
         option.innerHTML = "See all results:";
         locationSelect.appendChild(option);
       

       function searchLocationsNear(center) 
         clearLocations();

         var radius = document.getElementById('radiusSelect').value;
         var searchUrl = 'storelocator.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
         downloadUrl(searchUrl, function(data) 
           var xml = parseXml(data);
           var markerNodes = xml.documentElement.getElementsByTagName("marker");
           var bounds = new google.maps.LatLngBounds();
           for (var i = 0; i < markerNodes.length; i++) 
             var id = markerNodes[i].getAttribute("id");
             var name = markerNodes[i].getAttribute("name");
             var address = markerNodes[i].getAttribute("address");
             var distance = parseFloat(markerNodes[i].getAttribute("distance"));
             var latlng = new google.maps.LatLng(
                  parseFloat(markerNodes[i].getAttribute("lat")),
                  parseFloat(markerNodes[i].getAttribute("lng")));

             createOption(name, distance, i);
             createMarker(latlng, name, address);
             bounds.extend(latlng);
           
           map.fitBounds(bounds);
           locationSelect.style.visibility = "visible";
           locationSelect.onchange = function() 
             var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
             google.maps.event.trigger(markers[markerNum], 'click');
           ;
         );
       

       function createMarker(latlng, name, address) 
          var html = "<b>" + name + "</b> <br/>" + address;
          var marker = new google.maps.Marker(
            map: map,
            position: latlng
          );
          google.maps.event.addListener(marker, 'click', function() 
            infoWindow.setContent(html);
            infoWindow.open(map, marker);
          );
          markers.push(marker);
        

       function createOption(name, distance, num) 
          var option = document.createElement("option");
          option.value = num;
          option.innerHTML = name;
          locationSelect.appendChild(option);
       

       function downloadUrl(url, callback) 
          var request = window.ActiveXObject ?
              new ActiveXObject('Microsoft.XMLHTTP') :
              new XMLHttpRequest;

          request.onreadystatechange = function() 
            if (request.readyState == 4) 
              request.onreadystatechange = doNothing;
              callback(request.responseText, request.status);
            
          ;

          request.open('GET', url, true);
          request.send(null);
       

       function parseXml(str) 
          if (window.ActiveXObject) 
            var doc = new ActiveXObject('Microsoft.XMLDOM');
            doc.loadXML(str);
            return doc;
           else if (window.DOMParser) 
            return (new DOMParser).parseFromString(str, 'text/xml');
          
       

       function doNothing() 
  </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAVD0ngfhOFs5rnww7UFyz9rN6UznOIZ1U&callback=initMap">
    </script>
  </body>
</html>

使用上面的方法我可以指向单点,但我想要的是得到半径以上提供的每个纬度周围的位置是5 km

【问题讨论】:

请提供足够的示例并分享一些您遇到问题的代码。 【参考方案1】:

如果您已经在使用 Google 地图,那么我认为您可以尝试使用 computeDistanceBetween。

这是一个如何使用它的简短示例。您只需要消除那些大于您设置的半径的距离即可。

var home = ['Store', new google.maps.LatLng(29.520130, -98.415542)];

var pts = [
  ['Client A', new google.maps.LatLng(29.5197902, -98.3867079)],
  ['Client B', new google.maps.LatLng(29.5165967, -98.4235714)],
  ['Client C', new google.maps.LatLng(29.5198805, -98.3676648)]
];

var dist = google.maps.geometry.spherical.computeDistanceBetween;

pts.forEach(function(pt) 
  console.log(home[0] + ' to ' + pt[0] + ': ' + (dist(home[1], pt[1])).toFixed(10));
);

【讨论】:

以上是关于Javascript查找经纬度和半径的位置的主要内容,如果未能解决你的问题,请参考以下文章

python:使用纬度和经度查找提供位置半径内的位置的优雅方法

如何在经纬度半径范围内的 xml 文件中查找位置

从给定位置(经度、纬度)的 Y 半径内查找 X 的所有值

查找具有纬度和经度的记录[重复]

给定 GPS 的地理位置,如何在给定的 x 米半径内找到纬度和经度

从R中的已知中心点查找半径内的纬度/经度