For each organization it is important to show on a site in the contact section how to get there.
In this post I will show you an example of how to do it, using Google Maps v3 API.
Recently in Google Maps it has become possible to build routes all over the world.
Let’s look at example in action.
When you go to the page, we see the map above which there are fields to enter the address of departure and arrival (arrival address is already entered and has the value Shorina St., 13), and on the right side will be shown a route map and the total distance is calculated.
We start to enter the name of the street of departure and there is an automatic prompt of the street name, we choose the right one and click Find.
The route is built on the map, and the itinerary for it is displayed on the right.
Now let’s see the code of our example.
In the very beginning we connect the API Google Maps v3 and specify additional parameter language=en – it is necessary to output the itinerary in Russian.
We set the necessary styles for displaying and global variables for the map and the route.
After this we determine the initial parameters of the map.
How the route is calculated.
We pass the values of the form fields into the start and end variables for the start and end of the route, respectively.
The directionsService.route() function is used for construction of the optimal route, and we need to pass the necessary parameters to it.
origin – the point where the route will start destination – the point the route will end at waypoints – the array of points to avoid optimizeWaypoints – the feature to optimize points in the array. In our case it must be set to true, then the order of waypoints will not be important for the algorithm.
* travelMode – the sign of what kind of transport is used. We are looking for a route for the car, so you must set the value google.maps.TravelMode.DRIVING.
After calling the directionsService.route() function, you must check the result of the construction (status == google.maps.DirectionsStatus.OK).
The function computeTotalDistance – calculates the total distance of the route.
The item with ID=directionsPanel displays information about the path of the route.
And this script implements the automatic filling of the street name.
For this purpose in a database the table with the street names of Nizhny Novgorod street_nn was created. The data were taken here (Nizhny Novgorod post offices).
PHP-script rpc.php generates a query to the database with the output of 10 records from the table street_nn.
Functions lookup and fill are designed to implement autocomplete.
At the end of the note I will give another example, where the route is not just built, but there is an animation of the movement along the route.