machineaddict
machineaddict

Reputation: 3236

How do i get google map v3 direction coordinates from start to end

I have an application with google maps v3 and php. I need to dynamically add direction routes to google map and insert them in database with php. The working example is http://pastehtml.com/view/blzvshf3l.html and the code is this:

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Add Route</title>
    <style>
html, body {
    margin: 0;
    padding: 0;
}

#map_canvas {
    height: 600px;
    margin-bottom:20px;
}

@media print {
    html, body {
        height: auto;
    }

    #map_canvas {
        height: 650px;
    }
}

#controls{
    margin-bottom:20px;
}
#debug{
    height:200px;
    overflow:auto;
    margin-bottom:20px;
}
#description{
    margin-bottom:20px;
}
</style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

    <script type="text/javascript">
    var map;
    var markers = [];
    var directions = [];

    function initialize() {
        var bm = new google.maps.LatLng(47.65668913620708, 23.56867790222168);
        var myOptions = {
            zoom: 16,
            center: bm,
            minZoom: 13,
            maxZoom: 17,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

        google.maps.event.addListener(map, 'click', addRoute);
    }

    function addRoute(event) {
        if(markers.length < 2){
            var marker = new google.maps.Marker({
                position: event.latLng,
                map: map,
                draggable: true
            });
            markers.push(marker);
        }

        if(markers.length == 2){
            var start = markers[0].getPosition();
            var end = markers[1].getPosition();
            putDirections(start, end);

            $(markers).each(function(i, marker){
                google.maps.event.addListener(marker, 'dragend', function(){
                    clearDirections();
                    var start = markers[0].getPosition();
                    var end = markers[1].getPosition();
                    putDirections(start, end);
                });
            });
        }
    }

    function putDirections(start, end){
        var direction = [];

        var polylineOptions = {
            map: map,
            strokeColor: '#000000',
            strokeOpacity: 1.0,
            strokeWeight: 5
        }
        direction['directionsDisplay'] = new google.maps.DirectionsRenderer({
            polylineOptions: polylineOptions,
            suppressInfoWindows: true
        });
        direction['directionsDisplay'].suppressMarkers = true;
        direction['directionsDisplay'].preserveViewport = true;
        direction['directionsDisplay'].draggable = true;

        direction['directionsService'] = new google.maps.DirectionsService();

        var request = {
            origin:start,
            destination:end,
            travelMode: google.maps.DirectionsTravelMode.WALKING //DRIVING, WALKING, BICYCLING
        };
        direction['directionsDisplay'].setMap(map);

        direction['directionsService'].route(request, function(response, status){
            if(status == google.maps.DirectionsStatus.OK){
                direction['directionsDisplay'].setDirections(response);
            }
        });

        directions.push(direction);
    }

    function clearMarkers(){
        $(markers).each(function(i, marker){
            marker.setMap(null);
        });
        markers = [];
    }

    function clearDirections(){
        $(directions).each(function(i, direction){
            direction['directionsDisplay'].setMap(null);
        });
        directions = [];
    }

    function clearDebug(){
        $('#debug').html('');
    }

    function debug(){
        clearDebug();
        var debug = '';
        $(markers).each(function(i, marker){
            debug += '<b>Marker #'+(i+1)+'</b> position: latitude=<b>'+marker.getPosition().lat()+'</b>, longitude=<b>'+marker.getPosition().lng()+'</b><br>';
        });
        if(markers.length == 0){
            debug += 'Add some markers first!';
        }
        $('#debug').html(debug);
    }
    $(document).ready(function(){
        initialize();
    });
    </script>

</head>
<body>
    <div id="map_canvas"></div>
    <div id="controls">
        <input type="button" value="Reset Directions and Markers" onclick="clearMarkers();clearDirections();clearDebug();">
        <input type="button" value="Get Markers Location" onclick="debug();">
    </div>
    <div id="description">

        <strong>Description:</strong><br>

        Markers and routes can be dragged to create a new directions. They can also be deleted.
    </div>
    <div id="debug"></div>
</body>
</html>

I will need to be able to change (drag) the route (the example does that). The question is: how do i get all the coordinates (lat, lng) for all the routes between 2 points (markers)? i need to have draw the direction back from database to the map.

I was able to get the first set of coordinates between 2 points, like this:

 directions[0]['directionsDisplay'].getDirections().routes[0].overview_path

which is an array of coordinates. Is this the right way of getting the coordinates? What is the event name when i drag the route?

Upvotes: 3

Views: 8755

Answers (2)

Chris Broadfoot
Chris Broadfoot

Reputation: 5112

overview_path will only get you an overview (i.e. a simplified line). If that's fine for your use case, definitely use that. Otherwise, read on.

The DirectionsRoute object has a legs property. This is an array of DirectionsLeg objects, which in turn has a property of steps. Each DirectionsStep has a path.

If you collect all the paths for all the steps for all the legs, you'll be able to construct a detailed path for the whole route.

Additionally, once you do this, if you want to reduce the size that you send back to your PHP server, use the encoding library to compress the path.


Consider using the Directions API, accessible as a web service from PHP. In particular, you'll probably want to take the waypoints from the user defined path (dragged) and send those to your server so it can run the appropriate Directions API


The event that's fired when the user finishes dragging the path is called directions_changed. See the reference for DirectionsRenderer.

Upvotes: 5

anders.norgaard
anders.norgaard

Reputation: 1080

have you looked at the network traffic when you move the waypoints?

AJAX results are returned that contain info like

"overview_polyline" : { "points" : "yd{aHkwwnCAzM\jC~AdMnA|KTpBeGv@{@qS}A_^hCYb@MrDqBTa@Lc@Dc@@Oa@oDWoCi@wHw@uLMoCG_CEqHA]D?BEFK@Ib@a@lEaCdJaF|AgALQFQFURgCZiKJ[DO?KEIAs@DeB" }, `

If you can decode the "points" info that might be interesting.

Upvotes: 0

Related Questions