计算4个位置之间的距离

时间:2016-07-26 00:58:26

标签: google-maps-api-3 distance

我在网上找到了这个非常好的代码,用于计算2个位置之间的距离。 来源http://1stwebdesigner.com/distance-finder-google-maps-api/#saving-map

我正在尝试更改代码以添加2个航点,并计算4个位置之间的总距离。

我相信这个问题以前没有得到回答,对于那些希望在项目中实施类似内容的人来说也会有很大的好处。

我做了一些改动,但我坚持这一点。

if (status == google.maps.DirectionsStatus.OK) 
            {
                directionsDisplay.setDirections(response);
                distance = "The distance between the two points on the chosen route is: "+response.routes[0].legs[0].distance.text;
                distance += "<br/>The aproximative driving time is: "+response.routes[0].legs[0].duration.text;
                document.getElementById("distance_road").innerHTML = distance;
            }

此外,我不确定我是否在此位中正确添加了航点?

    var request = {
        origin:location1, 
        waypoints: [
        {
            location:location2,
        },{
            location:location3,
        }],
        destination:location4,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

此处完全修改代码

<html>
<head>
<title>Distance finder</title>
<meta type="description" content="Find the distance between two places on the map and the shortest route."/>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">

    var location1;
    var location2;
    var location3;
    var location4;

    var address1;
    var address2;
    var address3;
    var address4;

    var latlng;
    var geocoder;
    var map;

    var distance;

    // finds the coordinates for the two locations and calls the showMap() function
    function initialize()
    {
        geocoder = new google.maps.Geocoder(); // creating a new geocode object

        // getting the two address values
        address1 = document.getElementById("address1").value;
        address2 = document.getElementById("address2").value;
        address3 = document.getElementById("address3").value;
        address4 = document.getElementById("address4").value;

        // finding out the coordinates
        if (geocoder) 
        {
            geocoder.geocode( { 'address': address1}, function(results, status) 
            {
                if (status == google.maps.GeocoderStatus.OK) 
                {
                    //location of first address (latitude + longitude)
                    location1 = results[0].geometry.location;
                } else 
                {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
            geocoder.geocode( { 'address': address2}, function(results, status) 
            {
                if (status == google.maps.GeocoderStatus.OK) 
                {
                    //location of first address (latitude + longitude)
                    location2 = results[0].geometry.location;
                } else 
                {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
            geocoder.geocode( { 'address': address3}, function(results, status) 
            {
                if (status == google.maps.GeocoderStatus.OK) 
                {
                    //location of first address (latitude + longitude)
                    location3 = results[0].geometry.location;
                } else 
                {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
            geocoder.geocode( { 'address': address4}, function(results, status) 
            {
                if (status == google.maps.GeocoderStatus.OK) 
                {
                    //location of second address (latitude + longitude)
                    location4 = results[0].geometry.location;
                    // calling the showMap() function to create and show the map 
                    showMap();
                } else 
                {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
        }
    }

    // creates and shows the map
    function showMap()
    {
        // center of the map (compute the mean value between the two locations)
        latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,(location1.lng()+location2.lng())/2);

        // set map options
            // set zoom level
            // set center
            // map type
        var mapOptions = 
        {
            zoom: 1,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        // create a new map object
            // set the div id where it will be shown
            // set the map options
        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

        // show route between the points
        directionsService = new google.maps.DirectionsService();
        directionsDisplay = new google.maps.DirectionsRenderer(
        {
            suppressMarkers: true,
            suppressInfoWindows: true
        });
        directionsDisplay.setMap(map);
        var request = {
            origin:location1, 
            waypoints: [
            {
                location:location2,
            },{
                location:location3,
            }],
            destination:location4,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) 
        {
            if (status == google.maps.DirectionsStatus.OK) 
            {
                directionsDisplay.setDirections(response);
                distance = "The distance between the two points on the chosen route is: "+response.routes[0].legs[0].distance.text;
                distance += "<br/>The aproximative driving time is: "+response.routes[0].legs[0].duration.text;
                document.getElementById("distance_road").innerHTML = distance;
            }
        });

        // show a line between the two points
    //  var line = new google.maps.Polyline({
    //      map: map, 
    //      path: [location1, location2],
    //      strokeWeight: 7,
    //      strokeOpacity: 0.8,
    //      strokeColor: "#FFAA00"
    //  });

        // create the markers for the two locations     
        var marker1 = new google.maps.Marker({
            map: map, 
            position: location1,
            title: "First location"
        });
        var marker2 = new google.maps.Marker({
            map: map, 
            position: location2,
            title: "Second location"
        });
        var marker3 = new google.maps.Marker({
            map: map, 
            position: location3,
            title: "Third location"
        });
        var marker4 = new google.maps.Marker({
            map: map, 
            position: location4,
            title: "Fourth location"
        });
        // create the text to be shown in the infowindows
        var text1 = '<div id="content">'+
                '<h1 id="firstHeading">First location</h1>'+
                '<div id="bodyContent">'+
                '<p>Coordinates: '+location1+'</p>'+
                '<p>Address: '+address1+'</p>'+
                '</div>'+
                '</div>';

        var text2 = '<div id="content">'+
            '<h1 id="firstHeading">Second location</h1>'+
            '<div id="bodyContent">'+
            '<p>Coordinates: '+location2+'</p>'+
            '<p>Address: '+address2+'</p>'+
            '</div>'+
            '</div>';

        var text3 = '<div id="content">'+
            '<h1 id="firstHeading">Third location</h1>'+
            '<div id="bodyContent">'+
            '<p>Coordinates: '+location3+'</p>'+
            '<p>Address: '+address3+'</p>'+
            '</div>'+
            '</div>';

        var text4 = '<div id="content">'+
            '<h1 id="firstHeading">Fourth location</h1>'+
            '<div id="bodyContent">'+
            '<p>Coordinates: '+location4+'</p>'+
            '<p>Address: '+address4+'</p>'+
            '</div>'+
            '</div>';

        // create info boxes for the two markers
        var infowindow1 = new google.maps.InfoWindow({
            content: text1
        });
        var infowindow2 = new google.maps.InfoWindow({
            content: text2
        });
        var infowindow3 = new google.maps.InfoWindow({
            content: text3
        });
        var infowindow4 = new google.maps.InfoWindow({
            content: text4
        });

        // add action events so the info windows will be shown when the marker is clicked
        google.maps.event.addListener(marker1, 'click', function() {
            infowindow1.open(map,marker1);
        });
        google.maps.event.addListener(marker2, 'click', function() {
            infowindow2.open(map,marker1);
        });
        google.maps.event.addListener(marker3, 'click', function() {
            infowindow3.open(map,marker1);
        });
        google.maps.event.addListener(marker4, 'click', function() {
            infowindow4.open(map,marker1);
        });

        // compute distance between the two points
        var R = 6371; 
        var dLat = toRad(location2.lat()-location1.lat());
        var dLon = toRad(location2.lng()-location1.lng()); 

        var dLat1 = toRad(location1.lat());
        var dLat2 = toRad(location2.lat());

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


    }

    function toRad(deg) 
    {
        return deg * Math.PI/180;
    }
</script>

</head>

<body bgcolor="#eeeeee">
    <div id="form" style="width:100%; height:20%">
        <table align="center" valign="center">
            <tr>
                <td colspan="7" align="center"><b>Find the distance between two locations</b></td>
            </tr>
            <tr>
                <td colspan="7">&nbsp;</td>
            </tr>
            <tr>
                <td>First address:</td>
                <td>&nbsp;</td>
                <td><input type="text" name="address1" id="address1" size="50"/></td>
                <td>&nbsp;</td>
                <td>Second address:</td>
                <td>&nbsp;</td>
                <td><input type="text" name="address2" id="address2" size="50"/></td>
                <td>Third address:</td>
                <td>&nbsp;</td>
                <td><input type="text" name="address3" id="address3" size="50"/></td>
                <td>Fourth address:</td>
                <td>&nbsp;</td>
                <td><input type="text" name="address4" id="address4" size="50"/></td>
            </tr>
            <tr>
                <td colspan="7">&nbsp;</td>
            </tr>
            <tr>
                <td colspan="7" align="center"><input type="button" value="Show" onclick="initialize();"/></td>
            </tr>
        </table>
    </div>
    <center><div style="width:100%; height:10%" id="distance_direct"></div></center>
    <center><div style="width:100%; height:10%" id="distance_road"></div></center>

    <center><div id="map_canvas" style="width:70%; height:54%"></div></center>
</body>
</html>

完整原始代码

<html>
<head>
<title>Distance finder</title>
<meta type="description" content="Find the distance between two places on the map and the shortest route."/>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">

    var location1;
    var location2;

    var address1;
    var address2;

    var latlng;
    var geocoder;
    var map;

    var distance;

    // finds the coordinates for the two locations and calls the showMap() function
    function initialize()
    {
        geocoder = new google.maps.Geocoder(); // creating a new geocode object

        // getting the two address values
        address1 = document.getElementById("address1").value;
        address2 = document.getElementById("address2").value;

        // finding out the coordinates
        if (geocoder) 
        {
            geocoder.geocode( { 'address': address1}, function(results, status) 
            {
                if (status == google.maps.GeocoderStatus.OK) 
                {
                    //location of first address (latitude + longitude)
                    location1 = results[0].geometry.location;
                } else 
                {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
            geocoder.geocode( { 'address': address2}, function(results, status) 
            {
                if (status == google.maps.GeocoderStatus.OK) 
                {
                    //location of second address (latitude + longitude)
                    location2 = results[0].geometry.location;
                    // calling the showMap() function to create and show the map 
                    showMap();
                } else 
                {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
        }
    }

    // creates and shows the map
    function showMap()
    {
        // center of the map (compute the mean value between the two locations)
        latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,(location1.lng()+location2.lng())/2);

        // set map options
            // set zoom level
            // set center
            // map type
        var mapOptions = 
        {
            zoom: 1,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.HYBRID
        };

        // create a new map object
            // set the div id where it will be shown
            // set the map options
        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

        // show route between the points
        directionsService = new google.maps.DirectionsService();
        directionsDisplay = new google.maps.DirectionsRenderer(
        {
            suppressMarkers: true,
            suppressInfoWindows: true
        });
        directionsDisplay.setMap(map);
        var request = {
            origin:location1, 
            destination:location2,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) 
        {
            if (status == google.maps.DirectionsStatus.OK) 
            {
                directionsDisplay.setDirections(response);
                distance = "The distance between the two points on the chosen route is: "+response.routes[0].legs[0].distance.text;
                distance += "<br/>The aproximative driving time is: "+response.routes[0].legs[0].duration.text;
                document.getElementById("distance_road").innerHTML = distance;
            }
        });

        // show a line between the two points
        var line = new google.maps.Polyline({
            map: map, 
            path: [location1, location2],
            strokeWeight: 7,
            strokeOpacity: 0.8,
            strokeColor: "#FFAA00"
        });

        // create the markers for the two locations     
        var marker1 = new google.maps.Marker({
            map: map, 
            position: location1,
            title: "First location"
        });
        var marker2 = new google.maps.Marker({
            map: map, 
            position: location2,
            title: "Second location"
        });

        // create the text to be shown in the infowindows
        var text1 = '<div id="content">'+
                '<h1 id="firstHeading">First location</h1>'+
                '<div id="bodyContent">'+
                '<p>Coordinates: '+location1+'</p>'+
                '<p>Address: '+address1+'</p>'+
                '</div>'+
                '</div>';

        var text2 = '<div id="content">'+
            '<h1 id="firstHeading">Second location</h1>'+
            '<div id="bodyContent">'+
            '<p>Coordinates: '+location2+'</p>'+
            '<p>Address: '+address2+'</p>'+
            '</div>'+
            '</div>';

        // create info boxes for the two markers
        var infowindow1 = new google.maps.InfoWindow({
            content: text1
        });
        var infowindow2 = new google.maps.InfoWindow({
            content: text2
        });

        // add action events so the info windows will be shown when the marker is clicked
        google.maps.event.addListener(marker1, 'click', function() {
            infowindow1.open(map,marker1);
        });
        google.maps.event.addListener(marker2, 'click', function() {
            infowindow2.open(map,marker1);
        });

        // compute distance between the two points
        var R = 6371; 
        var dLat = toRad(location2.lat()-location1.lat());
        var dLon = toRad(location2.lng()-location1.lng()); 

        var dLat1 = toRad(location1.lat());
        var dLat2 = toRad(location2.lat());

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

        document.getElementById("distance_direct").innerHTML = "<br/>The distance between the two points (in a straight line) is: "+d;
    }

    function toRad(deg) 
    {
        return deg * Math.PI/180;
    }
</script>

</head>

<body bgcolor="#eeeeee">
    <div id="form" style="width:100%; height:20%">
        <table align="center" valign="center">
            <tr>
                <td colspan="7" align="center"><b>Find the distance between two locations</b></td>
            </tr>
            <tr>
                <td colspan="7">&nbsp;</td>
            </tr>
            <tr>
                <td>First address:</td>
                <td>&nbsp;</td>
                <td><input type="text" name="address1" id="address1" size="50"/></td>
                <td>&nbsp;</td>
                <td>Second address:</td>
                <td>&nbsp;</td>
                <td><input type="text" name="address2" id="address2" size="50"/></td>
            </tr>
            <tr>
                <td colspan="7">&nbsp;</td>
            </tr>
            <tr>
                <td colspan="7" align="center"><input type="button" value="Show" onclick="initialize();"/></td>
            </tr>
        </table>
    </div>
    <center><div style="width:100%; height:10%" id="distance_direct"></div></center>
    <center><div style="width:100%; height:10%" id="distance_road"></div></center>

    <center><div id="map_canvas" style="width:70%; height:54%"></div></center>
</body>
</html>

0 个答案:

没有答案