javascript - gmaps.js,找到最近的点

标签 javascript geolocation

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

最佳答案

这应该可以解决问题。我结合了 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>

关于javascript - gmaps.js,找到最近的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21902647/

相关文章:

javascript - 用于捕获完整文件路径/UNC 的 Web 对话框

javascript - html/js/jquery 检测不可伪造的手机位置

geolocation - GPS坐标的国家/地区名称

javascript - 计算地理位置时无法设置外部(全局?)变量

javascript - 多次调用子组件构造函数

javascript - 获取 ng Repeat 中第一行的第一个值

javascript - 使用正则表达式计算字符串中引号的数量

javascript - 使用地理位置获取城市名称

google-chrome - 地理位置 - 位于 'https://www.googleapis.com/' : Returned error code 400 的网络位置提供商

javascript - 检测是否单击了 div 的背景图像的一部分