Saving draggable directions waypoints in google maps v3. Save google directions waypoints in database and retrive it back to display
1.Introduction 2.Demo 3.Code and Explanation 4.Saving Waypoints 5.Download Source Code 6.Comments
Introduction
This document is about creating a google map with directions and creating waypoints between those directions and saving them in the database, fetching the waypoints from the database to be displayed in the front end. So this document is primarily about saving google directions waypoints in database and retrieving them to be displayed again.
Additional Information about google direction service waypoints
Google Maps V3 has directions service using which we can display a direction from a start place to end place. The direction can be dragged to change the route. So it is referred as draggable directions. When the map loads we set a start point and end point between these a direction (route) is displayed. The user can click on the direction(route) and drag in any direction to change the route. When you do so you mean a different route than the default. Here a mark is made and is called the way point. So you create waypoints between a normal route to show the difference in the actual route and the modified route through waypoints. You can create max of 8 waypoints.Mostly people want to show directions to the users by creating or defining it in their admin section of their website. So here in this tutorial i have written and explained how to save those waypoints in the database. And further there is code to retrieve the waypoints from the database to display it to the user. So what ever directions waypoints you have made in the admin section it will reflect in the front end. That is the scope of this document. Here you have explanation and sample code to save waypoints which includes a sample code to save the waypoints, a database structure with table and a default value and code sample to display the waypoints from the database to the front end.
Click on the route in blue and drag it to other place | Click the button below to fetch the saved data | |
Code and Explanation
Include the following code in your head section. The first one will include google map version 3 api and the second is used to create json string from an array or an object using this we will convert the waypoints to json format and we will post it to the server which will be saved in the database..
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script src="json2.js"></script>
Create a div with id mappy and your own style. Create a button which when clicked will call a javascript function to save the waypoints. When the document is loaded the function goma() is called which will initialize the map.
<body onLoad="goma()"> <div id="mappy" style="width:900px; height:550px;"></div> <div style="width:900px; text-align:center; margin:0px auto 0px auto; margin-top:10px;"> <input type="button" value="Save Waypoints" onClick="save_waypoints()"> </div> </body>
Let us see the following function in detail.
Line no 1 and 2 declares variables for direction service and direction render service and a map object. variable data will hold the start location, end location and waypoints in latitude and longitude.
In line 5 we initialize the map by passing the id of the div where the map will be displayed and as the second parameter we pass all the needful parameters to the map as objects like zoom level, and map type and the center of the map. Since you would have already worked in google map i am leaving the basic stuff to yourself while we concentrate on the main functionality.
ser.route will get the start location, end location, driving mode and a callback function.
This will send a request to google server to get a path in result which will be rendered using the callback function
In the callback function if the response is ok then the result is assigned to the setdirections function which will draw the route in the google map set by ren.setMap(map).
Now you got the directions in blue color on the map.
var map, ren, ser; var data = {}; function goma() { map = new google.maps.Map( document.getElementById('mappy'), {'zoom':12, 'mapTypeId': google.maps.MapTypeId.ROADMAP, 'center': new google.maps.LatLng(26.05678288577881, -80.30236816615798) }) ren = new google.maps.DirectionsRenderer( {'draggable':true} ); ren.setMap(map); ser = new google.maps.DirectionsService(); ser.route({ 'origin': new google.maps.LatLng(26.104887637199948, -80.39231872768141), 'destination': new google.maps.LatLng(25.941991877144947, -80.16160583705641), 'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) { if(sts=='OK')ren.setDirections(res); }) }
The Main Picture - Saving waypoints
Now let us see what happens in the main picture where we create a json string and save the waypoints in the database.
When ever you drag the direction to create a way point the ren objects routes gets updated with the new waypoints. If you had created two waypoints then rleg.via_waypoints.length will be 2 of array type. Now we need the start location, the end location and the waypoints. The variable wp in line number 7 will contain the array of waypoints. what i have done in the for loop is i am taking only the latlng from the waypoint object. so i create an array of latlng. so now we have data.start, data.end and data.waypoints. data.waypoints furtuer is an array of waypoints as latlng. finally we have the object data and we are going to convert it to a json string using the json's stringify method. and we got a string that can be sent to the server to be saved in the database using ajax.
And i hope you know how ajax works. the code posts the json string to the server script process.php. We send two key value pairs one is the key command which will have the value save and another is the key mapdata which will hold the json string of start, end and waypoints.
function save_waypoints() { var w=[],wp; var rleg = ren.directions.routes[0].legs[0]; data.start = {'lat': rleg.start_location.lat(), 'lng':rleg.start_location.lng()} data.end = {'lat': rleg.end_location.lat(), 'lng':rleg.end_location.lng()} var wp = rleg.via_waypoints for(var i=0;i<wp.length;i++)w[i] = [wp[i].lat(),wp[i].lng()] data.waypoints = w; var str = JSON.stringify(data) var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); jax.open('POST','process.php'); jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); jax.send('command=save&mapdata='+str) jax.onreadystatechange = function(){ if(jax.readyState==4) { if(jax.responseText.indexOf('bien')+1)alert('Updated'); else alert(jax.responseText) }} }
The following is the server script process.php which will receive the start, end and waypoints from the client side to store it in the database.
In the database mapdir i have a table that too named mapdir which has one field named "value". That table will have an empty row so we need not use insert. I fetch the mapdata from $_REQUEST['mapdata'] and update the value field of mapdir table. So now the waypoints are saved in the database.
Next what we are going to see is how to fetch the saved data and to display the directions in the front end.
ob_start(); header('Cache-Control: no-store, no-cache, must-revalidate'); $data = $_REQUEST['mapdata']; mysql_connect('localhost','root',''); mysql_select_db('mapdir'); if($_REQUEST['command']=='save') { $query = "update mapdir set value='$data'"; if(mysql_query($query))die('bien'); die(mysql_error()); } if($_REQUEST['command']=='fetch') { $query = "select value from mapdir"; if(!($res = mysql_query($query)))die(mysql_error()); $rs = mysql_fetch_array($res,1); die($rs['value']); }
First we create a div with id mappy and in body onload we call the function goma which will initialise the map data with the specified zoom value, maptype and the center location. all which you can set it according to your own preference. And then i call a function fetchdata which will read the start point, end point and the waypoints from the database using ajax.
var map, ren, ser; var data = {}; function goma() { map = new google.maps.Map( document.getElementById('mappy'), {'zoom':12, 'mapTypeId': google.maps.MapTypeId.ROADMAP, 'center': new google.maps.LatLng(26.05678288577881, -80.30236816615798) }) ren = new google.maps.DirectionsRenderer( {'draggable':true} ); ren.setMap(map); ser = new google.maps.DirectionsService(); fetchdata() }
function fetchdata() { var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); jax.open('GET','process.php'); jax.send('command=fetch') jax.onreadystatechange = function(){ if(jax.readyState==4) { try { setroute( eval('(' + jax.responseText + ')') ); } catch(e){ alert(e); } }} }
if($_REQUEST['command']=='fetch') { $query = "select value from mapdir"; if(!($res = mysql_query($query)))die(mysql_error()); $rs = mysql_fetch_array($res,1); die($rs['value']); }
os.start.lat will have the start point and os.end.lat will have the end point and os.waypoints array will have the waypoints.
We need to create an array wp of objects which will have the latlng and stopover. Then we pass that variable wp to the route function with the start and end points. In the ser.setroute functions callback we display the direction.
function setroute(os) { var wp = []; for(var i=0;i<os.waypoints.length;i++) wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][1]),'stopover':false } ser.route({'origin':new google.maps.LatLng(os.start.lat,os.start.lng), 'destination':new google.maps.LatLng(os.end.lat,os.end.lng), 'waypoints': wp, 'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) { if(sts=='OK')ren.setDirections(res); }) }
Download Source Code
The zip file contains the html, php and sql files for marking waypoints, saving waypoints and to load the waypoints from the database.
Click here to download the saving waypoints from draggable directions source code
Comments, Suggestions, Objections, ...