2014-02-20 161 views
2

我有一個經緯度點的數組。接下來,我將所有點添加到我的地圖。 我需要解決方案/算法來移動用戶到我的陣列最近的點使用頁面加載geoloation。 (如果地理位置成功的話當然)gmaps.js,找到最近的點

+0

可能重複(http://stackoverflow.com/questions/14111734/finding-nearest-listed-array-city-from-known-location ) –

回答

5

這應該是個訣竅。我結合了HTML5地理位置查找用戶的當前位置和Haversine函數來計算距離一組位置和用戶當前位置的距離。這組位置在JS陣列的「位置」中定義。 [查找最近上市(數組?)城市從已知位置]的

<!DOCTYPE html> 
<html> 
<head> 
    <title>Google Map Template with Marker at User's Position</title> 
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> <!-- Google Maps API --> 
    <script> 

    // set of locations represented by lat/lon pairs 
    var locations = [{lat:45, lon:-120}, {lat:44, lon:-121}, {lat:45.6, lon:-120.5}]; 

    var map; // Google map object 

    // Initialize and display a google map 
    function Init() 
    { 
     // HTML5/W3C Geolocation 
     if (navigator.geolocation) 
     { 
      navigator.geolocation.getCurrentPosition(UserLocation, errorCallback,{maximumAge:60000,timeout:10000}); 
     } 
     // Default to Washington, DC 
     else 
      ClosestLocation(38.8951, -77.0367, "Washington, DC"); 
    } 

    function errorCallback(error) 
    { 
    } 

    // Callback function for asynchronous call to HTML5 geolocation 
    function UserLocation(position) 
    { 
     ClosestLocation(position.coords.latitude, position.coords.longitude, "This is my Location"); 
    } 

    // Display a map centered at the specified coordinate with a marker and InfoWindow. 
    function ClosestLocation(lat, lon, title) 
    { 
     // Create a Google coordinate object for where to center the map 
     var latlng = new google.maps.LatLng(lat, lon);  

     // Map options for how to display the Google map 
     var mapOptions = { zoom: 12, center: latlng }; 

     // Show the Google map in the div with the attribute id 'map-canvas'. 
     map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); 

     // Place a Google Marker at the same location as the map center 
     // When you hover over the marker, it will display the title 
     var marker = new google.maps.Marker({ 
      position: latlng,  
      map: map,  
      title: title 
     }); 

     // Create an InfoWindow for the marker 
     var contentString = "<b>" + title + "</b>"; // HTML text to display in the InfoWindow 
     var infowindow = new google.maps.InfoWindow({ content: contentString }); 

     // Set event to display the InfoWindow anchored to the marker when the marker is clicked. 
     google.maps.event.addListener(marker, 'click', function() { infowindow.open(map, marker); }); 

     // find the closest location to the user's location 
     var closest = 0; 
     var mindist = 99999; 

     for(var i = 0; i < locations.length; i++) 
     { 
      // get the distance between user's location and this point 
      var dist = Haversine(locations[ i ].lat, locations[ i ].lon, lat, lon); 

      // check if this is the shortest distance so far 
      if (dist < mindist) 
      { 
       closest = i; 
       mindist = dist; 
      } 
     } 

     // Create a Google coordinate object for the closest location 
     var latlng = new google.maps.LatLng(locations[ closest].lat, locations[ closest].lon);  

     // Place a Google Marker at the closest location as the map center 
     // When you hover over the marker, it will display the title 
     var marker2 = new google.maps.Marker({ 
      position: latlng,  
      map: map,  
      title: "Closest Location to User: Distance is " + mindist + " km" 
     }); 

     // Create an InfoWindow for the marker 
     var contentString = "<b>" + "Closest Location to User: Distance is " + mindist + " km" + "</b>"; // HTML text to display in the InfoWindow 
     var infowindow = new google.maps.InfoWindow({ content: contentString }); 

     // Set event to display the InfoWindow anchored to the marker when the marker is clicked. 
     google.maps.event.addListener(marker2, 'click', function() { infowindow.open(map, marker2); }); 

     map.setCenter(latlng); 
    } 

    // Call the method 'Init()' to display the google map when the web page is displayed (load event) 
    google.maps.event.addDomListener(window, 'load', Init); 

    </script> 
    <script> 
    // Convert Degress to Radians 
    function Deg2Rad(deg) { 
     return deg * Math.PI/180; 
    } 

    // Get Distance between two lat/lng points using the Haversine function 
    // First published by Roger Sinnott in Sky & Telescope magazine in 1984 (「Virtues of the Haversine」) 
    // 
    function Haversine(lat1, lon1, lat2, lon2) 
    { 
     var R = 6372.8; // Earth Radius in Kilometers 

     var dLat = Deg2Rad(lat2-lat1); 
     var dLon = Deg2Rad(lon2-lon1); 

     var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
         Math.cos(Deg2Rad(lat1)) * Math.cos(Deg2Rad(lat2)) * 
         Math.sin(dLon/2) * Math.sin(dLon/2); 
     var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
     var d = R * c; 

     // Return Distance in Kilometers 
     return d; 
    } 

    // Get Distance between two lat/lng points using the Pythagoras Theorem on a Equirectangular projection to account 
    // for curvature of the longitude lines. 
    function PythagorasEquirectangular(lat1, lon1, lat2, lon2) 
    { 
     lat1 = Deg2Rad(lat1); 
     lat2 = Deg2Rad(lat2); 
     lon1 = Deg2Rad(lon1); 
     lon2 = Deg2Rad(lon2); 
     var R = 6371; // km 
     var x = (lon2-lon1) * Math.cos((lat1+lat2)/2); 
     var y = (lat2-lat1); 
     var d = Math.sqrt(x*x + y*y) * R; 
     return d; 
    } 




</script> 

    <style> 
    /* style settings for Google map */ 
    #map-canvas 
    { 
     width : 500px; /* map width */ 
     height: 500px; /* map height */ 
    } 
    </style> 
</head> 
<body> 
    <!-- Dislay Google map here --> 
    <div id='map-canvas' ></div> 
</body> 
</html> 
+0

你搖滾安德魯,非常感謝你的幫助。 –