Home » Php » php – Getting dragged route data out of Google Maps

php – Getting dragged route data out of Google Maps

Posted by: admin July 12, 2020 Leave a comment


I am working on a project and am at a point where I am unable to go any further and need some serious assistance. Let me give you some background.

I am working on a service that will let users riding bikes to the
same destination from multiple starting points coordinate their rides.
Part of the workflow we’ve designed has users building maps using the
Google Maps service; they enter a starting destination, Google creates
a route it thinks will work, and then users can tailor that route by
dragging points to meet their particular needs. We have this
interface developed and working nicely at:


Where I’ve hit an impassable wall is in how to get the user-edited
route out of Google Maps and saved in the database for future
reference. It seems like we have a method for doing that in our
Javascript, in this file (lines 344-352):


    var newString = JSON.stringify(directions);
    //set up area to place drop directionsResponse object string
    var directions_response_panel = document.getElementById("directions_response");
    //dump any contents in directions_response_panel
    directions_response_panel.innerHTML = "";
    //add JSON string to it 
    directions_response_panel.innerHTML = "<pre>" + newString + "</pre>";
    //run the ajax

We can get the route data out as a JSON file, stringify it, and send
it via AJAX to a PHP file where we intend to process it and store it
in MySQL. However, the JSON being returned from Google Maps appears
to be malformed; PHP freaks out when it tries to decode it, and I ran
it through a validator online which confirmed its malformness. It is
at this point that we are completely baffled and have no idea how to
move forward.

Is there any chance this anybody might be able to assist with this? I am at the point of bashing my head against a wall. Any response at all is greatly appreciated. Thanks for your time!

How to&Answers:

I have been doing similar thing and found this really difficult however after several hours of hard work, I managed to get all waypoints from User-Dragged route and save it into database..

So, I have a field that holds all waypoints separated by “;”.

You have to have this:

directionsDisplay = new google.maps.DirectionsRenderer({
    'map': map,
    'preserveViewport': true,
    'draggable': true

in your initialisation function

this is part of my JS:

var currentDirections;
var directionsDisplay;
var waypoints = [];
    function saveWaypoints()
        waypoints = [];
        var waypts_field = document.getElementById('waypoints').value.split(';');
        for(var bo = 0; bo < waypts_field.length; bo++)
            if(waypts_field[bo] == ' ' || waypts_field[bo] == '')
                bo -= 1;

            waypoints.push({ location: waypts_field[bo], stopover: false });

    function getWaypoints()
    currentDirections = directionsDisplay.getDirections();
    var route = currentDirections.routes[0];
    totalLegs = route.legs.length;
    for (var i = 0; i < route.legs.length; i++) {
        var routeSegment = i+1;
        if(route.legs[i].via_waypoint[0] === undefined) continue;

        document.getElementById('waypoints').value = '';
        var via_waypoint_count = route.legs[i].via_waypoint.length;
        queue = 0;
        for(var bi = 0; bi < via_waypoint_count; bi++)
            var count = 0;

            var lat;
            var lng;

            for (key in route.legs[i].via_waypoint[bi]['location'])
                if(count > 1) break;
                if(count == 0)
                    lat = route.legs[i].via_waypoint[bi]['location'][key];
                lng = route.legs[i].via_waypoint[bi]['location'][key];

            reverseGeoCode(new google.maps.LatLng(lat,lng));

        function reverseGeoCode(latlng)
        queue += 60;
        geocoder.geocode({ 'latLng': latlng }, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
              document.getElementById('waypoints').value += results[1].formatted_address + '; ';
          } else {
            alert("Geocoder failed due to: " + status);
        }, queue * 10);

i quickly pulled this off my JS, so if it does not make sense, I will post all of my JS and explain it bit by bit..



What you should do instead is create a new JSON in you JS which is not malformed and then pass this to PHP via AJAX, That will solve the problem of malformed JSON


I ran into the same issue and I have just solved it.

Storing the whole DirectionsResponse is totally unneccesary.
The DirectionsService.route returns a route based on a Hash that is passed to it.
So storing that Hash should be enough to store the route.

By the time, this might only become a different route when a better/faster way is available.

Let’s take a look at the request hash:

request = {
  origin: "Hamburg"
  destination: "Berlin"
  waypoints: [{location: new google.maps.LatLng(53.88,11.51), stopover: false}],
  travelMode: google.maps.DirectionsTravelMode.DRIVING

As previously mentioned by Crag, the data that is returned is JSON-like and not JSON.
So, when we store this data, we need to convert the JSON string into a JSON-like Hash again.
The waypoints that are going to be stored in the database by using JSON.stringify() looks like that:

  [location: {
      Ha: 53.88, 
      Ia: 11.51
    stopover: false

whenever you want to pass that data to DirectionsService.route you can simply call a function before which will overwrite each location with a LatLng object:

parse_route_request = function(request) {
  var waypoint, i, len;
  request = JSON.parse(request);
  for (i = 0, len = request.waypoints.length; i < len; i++) {
    waypoint = request.waypoints[_i];
    if (waypoint.location.Ha) {
      waypoint.location = new google.maps.LatLng(waypoint.location.Ha, waypoint.location.Ia);
  return request;