Programming
Copyright © 2019 Jiri Kriz, www.nosco.ch
Snippet so7860628
Back to Overview

How to make 'xx km' from Location, geo/google api


<!DOCTYPE html>
<!-- http://stackoverflow.com/a/7860628 -->
<html>
<head>
<script type="text/javascript"
    src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false">
</script>

<script type="text/javascript">
    function computeRestaurants() {
        spherical = google.maps.geometry.spherical;
        
        var pos = new google.maps.LatLng(55.662133, 12.508028);

        var r1 = {name: "rest1", lat: 55.667029, lng: 12.527715, dist: 0};
        var r2 = {name: "rest2", lat: 55.6939821, lng: 12.4934945, dist: 0};
        var r3 = {name: "rest3", lat: 55.6696885, lng: 12.3755492, dist: 0};

        var r = [r3, r2, r1];
        for (var i = 0; i < r.length; ++i) {
            var p = new google.maps.LatLng(r[i].lat, r[i].lng);
            var d = google.maps.geometry.spherical.computeDistanceBetween(pos, p);
            r[i].dist = d;
        }
        
        r.sort(function(r1, r2) {return r1.dist - r2.dist;});
        
        var elem = document.getElementById("restaurants");
        var restaurants = "";
        for (var i = 0; i < r.length; ++i) {
            var d = r[i].dist / 1000; // km
            restaurants += r[i].name + " dist: " + d.toFixed(1) + "km <br />";    
        }
        elem.innerHTML = restaurants;
      }
</script>
</head>

<body>
<div id="restaurants"></div>
<script type="text/javascript">
computeRestaurants();
</script>
</body>

</html>