Javascript gmaps.js,找到最近的点

Javascript gmaps.js,找到最近的点,javascript,geolocation,Javascript,Geolocation,我有一个带纬度和经度的点数组。接下来,我将所有点添加到地图中。 我需要解决方案/算法,以便在页面加载时使用geoloation将用户移动到距我的数组最近的点。 (当然,如果地理定位成功的话)这应该可以做到。我结合了HTML5地理定位来查找用户的当前位置,并结合Haversine函数来计算从一组位置到用户当前位置的距离。位置集在JS数组“位置”中定义 <!DOCTYPE html> <html> <head> <title>Google Ma

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

这应该可以做到。我结合了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>

在用户位置带有标记的Google地图模板
//由lat/lon对表示的位置集
变量位置=[{lat:45,lon:-120},{lat:44,lon:-121},{lat:45.6,lon:-120.5}];
变量映射;//谷歌地图对象
//初始化并显示谷歌地图
函数Init()
{
//HTML5/W3C地理定位
if(navigator.geolocation)
{
getCurrentPosition(UserLocation,errorCallback,{maximumAge:60000,timeout:10000});
}
//默认为华盛顿特区
其他的
关闭位置(38.8951,-77.0367,“华盛顿特区”);
}
函数errorCallback(错误)
{
}
//用于异步调用HTML5地理位置的回调函数
功能用户位置(位置)
{
ClosesLocation(position.coords.lation,position.coords.longitude,“这是我的位置”);
}
//使用标记和信息窗口显示以指定坐标为中心的地图。
功能关闭位置(lat、lon、title)
{
//为地图的居中位置创建Google坐标对象
var latlng=新的google.maps.latlng(lat,lon);
//如何显示谷歌地图的地图选项
var mapOptions={zoom:12,center:latlng};
//在div中显示属性id为“map canvas”的Google地图。
map=new google.maps.map(document.getElementById('map-canvas'),mapOptions);
//将谷歌标记放置在与地图中心相同的位置
//当您将鼠标悬停在标记上时,它将显示标题
var marker=new google.maps.marker({
位置:latlng,
地图:地图,
标题:标题
});
//为标记创建一个信息窗口
var contentString=“”+title+”;//要在信息窗口中显示的HTML文本
var infowindow=new google.maps.infowindow({content:contentString});
//Set event可在单击标记时显示定位到标记的信息窗口。
google.maps.event.addListener(标记,'click',function(){infowindow.open(映射,标记);});
//查找离用户位置最近的位置
var=0;
var mindist=99999;
对于(变量i=0;i