gmaps.js,找到最近的点

时间:2014-02-20 08:52:31

标签: javascript geolocation

我有一个经纬度点数组。接下来,我将所有点添加到我的地图中。 我需要解决方案/算法在页面加载时使用geoloation将用户移动到我的数组中最近的点。 (如果地理位置成功当然)

1 个答案:

答案 0 :(得分:5)

这应该可以解决问题。我结合了HTML5地理位置来查找用户的当前位置和Haversine功能来计算一组位置的距离和用户的当前位置。位置集在JS数组“locations”中定义。

<!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>