Google Maps API



Maps and Routing

Google Maps API

 

 image taken from https://atendesigngroup.com/blog/google-maps-javascript-api

 


What is it?

The topic today is the Google Maps API. It is a pretty big API, with many different functionalities, but we will focus on one: the JavaScript API. Its functionalities are similar to the one from Leaflet, as we will see later. Also, now we need to have basic knowledge of JavaScript, although it is pretty easy to use this API. Before you start, you need to get an API key here. 

This solution is still free to use for smaller projects, but for commercial use you might want to check the Google licences, so you can be sure everything is legal.

Just one note before we start: I will not show every example and the code for it, because everything is documented pretty well, but I will put the references on Googles documentation. Also, since I cannot embed the scripts in this blog, I will put references so you can see what it looks like.



Embed a basic map

After we have our API key, we can go on with embedding the map in our site. 

Basically, we create a <div> element, and manipulate it with javascript. The functions to do that are provided by Google, and have to be included in your HTML-page.

To show a basic map, we use the code suggested on the home site of the API which looks as follow: 

 <html>
  <head>
   <link href="/maps/documentation/javascript/demos/demos.css" rel="stylesheet"&gt;&lt;/link>  
  </head>
  <body>
   <div id="map">
 </div>
 <script>  
    function initMap() {  
     // Create a map object and specify the DOM element for display.  
     var map = new google.maps.Map(document.getElementById('map'), {  
      center: {lat: -34.397, lng: 150.644},  
      scrollwheel: false,  
      zoom: 8  
     });  
    }  
   </script&gt;  
   <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>  
  </body>
 </html>

Insert your API key in the last script tag, and you will get this result, also shown in the image below:
 

As you can see in the script above, the things needed to make a basic map are the coordinates of the location, and the zoom level you desire. You can add many more features, which you can see in the documentation. Here you can find code samples, with explanations, that should help you if you want to add more features to your map. I will now go through some of them.


Add Markers

One thing that the API has, and the direct embed solution doesn't have are markers: you can simply add one by adding the following code to your script:

 var marker = new google.maps.Marker(
   position: myLatLng,
   map: map
   title: 'Hello World!'
});

This will add a marker on the specified Location. Note that the variable myLatLng looks like this:

 var myLatLng = {lat: -25.363, lng: 131.044};   

As you can see, it is an array that contains both latitude and longitude to identify a point on the map. This makes it pretty easy to show different maps, or positions on the map, which is a main reason to choose the API: the possibility to adapt. You can simply have a variable that contains this information, and adapt it to the situation: if you want to show the marker in location A, use its coordinates, if you want the marker to be in location B just use other coordinates. The same goes for the location of the map, and most other elements we will see later.
Another useful feature is adding a marker when the map is clicked. You can do that with the following code:

// This event listener calls addMarker() when the map is clicked.    
google.maps.event.addListener(map, 'click', function(event) {
   addMarker(event.latLng, map);
});
// Adds a marker to the map at the clicked location
function addMarker(location, map) {
   var marker = new google.maps.Marker({
      position: location,
      map: map
   });
} 

Adding this code will allow you to add a marker on the clicked location. Here you can test this feature.


For further modifications, you should store all markers in an array. This can be done by adding a this code where you create the marker:

//Create the array
var markers = [];
function addMarker(location) {
   var marker = new google.maps.Marker({
      position: location,
      map: map
   });
//Push the created marker to the array
   markers.push(marker);
}   

To delete markers, simply call the clearMarkers() function. Example

Add shapes and strokes

Adding shapes and strokes is very similar to adding markers: you need the coordinates of the location you want to add them to, and then you call the constructor for the respective element. 



In this example, also shown in the image above, the flight route of the first trans-Pacific flight is shown with a line. As you can see, the coordinates are saved in an array, and the polyline is created using these coordinates and some further options.


var flightPlanCoordinates = [
   {lat: 37.772, lng: -122.214},
   {lat: 21.291, lng: -157.821},
   {lat: -18.142, lng: 178.431},
   {lat: -27.467, lng: 153.027
];
var flightPath = new google.maps.Polyline({
   path: flightPlanCoordinates,
   geodesic: true,
   strokeColor: '#FF0000',
   strokeOpacity: 1.0,
   strokeWeight: 2
});
flightPath.setMap(map);   

The same goes for the shapes, here you can find other examples for them.


Conclusion

As I mentioned before, I will not explain every little detail about the API, because there is already a good documentation for everything. I showed some of the most useful features according to my opinion, and put the references to more examples and explanations.

In conclusion, I would say that the Google Map API is a good solution, if you like the layout of the Google maps, the possibilities to modify a map are pretty similar to the ones of Leaflets, which I will explain later. The API key can be received without costs, and as long as you follow the Terms of Use, this solution should give you most options you need to create your default map for a website.
 

Leaflet

Maps and Routing

Leaflet

 

image taken from http://leafletjs.com/

 

What is it?

As stated on the official website, „Leaflet is the leading open-source JavaScript library for mobile-friendly interactive maps. Weighing just about 38 KB of JS, it has all the mapping features most developers ever need.
Leaflet is designed with simplicity, performance and usability in mind. It works efficiently across all major desktop and mobile platforms, can be extended with lots of plugins, has a beautiful, easy to use and well-documented API and a simple, readable source code that is a joy to contribute to.“ (http://www.leafletjs.com)
In the library we can find tools to create things we already created with Google Maps, like markers and popups, and many more. Leaflet itself does not provide the map, you have to specify which map you want to use. I will go with OpenStreetMap, as I already mentioned in previous chapters, because I like its layout and it offers routing for many types of transport, and also for hiking or bicycles. Now lets go on and see some basics of how to use Leaflets. (You can find the whole documentation here).



How to use Leaflet


Although there is a pretty good tutorial that explains its use really well, lets see what we need to do before we start creating a map. First of all, we need to include the stylesheet and the script with the following HTML-code:
<link rel="stylesheet" 
  href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css"/>
and
<script 
  src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"/>  
Now, we have to create a div-tag with an id, in my case “mapid” (make sure the div-tag has a height!). Now we are ready to instantiate our map with javascript:
//This will create a map object and already set the 
   view point, but does not contain map layers!  
var mymap = L.map('mapid').setView([51.505, -0.09], 13);  
//Now we have to add the so called tile layer to the map  
//Be sure to add the attribution!  
L.tileLayer(
   'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 
   {
      attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors',  
      maxZoom: 18,
   }
).addTo(mymap);  

In this case, I use the URL for OSM-tiles, if you want to use other maps, just search the right URL for it. Now we already have an OSM map on our website.



Add markers and other shapes

Adding markers is quite easy, you just need the coordinates:

var marker = L.marker([51.5, -0.09]).addTo(mymap);

We can also add popups to markers, just write

marker.bindPopup("<b>Hello world!</b><br>I am a popup.");  

As you can see, this is a really easy code that still gets us good results.

Here you can find the whole example.


Is it good?

I used Leaflet during my summer job, where I had to add a map to my website. i liked the idea of an open-source solution, and you have more control than with Google API, since you can choose the map you want to use. Both Leaflet and Google Maps API let you add very usefull features, like markers, shapes, etc. to your map. In the end, as I already mentioned a few times, you should choose the map that you like mos since you can get amazing results with all solutions. 

Example with Leaflet

Maps and Routing

A full example with Leaflet

Now that we have gone through many different possibilities to embed different maps and features on our website, I will end the blog with a full example of what it could look like. We will use Leaflet and OSM to create a map that has auto-routing, and where you can add markers for the start, stop and waypoints by clicking on the map. I will show the code used and explain it. To start it off, we need an HTML-page with a few includes. The code looks like this:
<!DOCTYPE html>  
<html>  
<head>;  
  <meta charset="utf-8" />  
  <title>Leaflet OSRM Example</title>  
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
  <script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
</head> 
<body>
  <div id="map" style="height: 500px; width: 1000px"></div> 
  <script src="index.js"></script>
</body>
</html>

Just be sure to call the index.js after you created the div.
Afterwards, go on to modify the index.js.

As mentioned in the last chapter, to create a basic map all you need is
 var map = L.map('map');  
 L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {  
   attribution: 'Map data © &amp;lt;a href="http://openstreetmap.org"&amp;gt;OpenStreetMap&amp;lt;/a&amp;gt; contributors',  
   maxZoom: 18,
 }).addTo(map);  
Now we already have an OpenStreetMap, which by default is centered in London. But since we want to add more features, we have to add some new code. First of all, we want to include a so-called router, which does the auto-routing for us. Since this is no basic feature of Leaflet, we have to download the plugin first. I use the Leaflet routing machine plugin of Per Liedman, a solution free to use but still very good. If you want to learn more details about it, check out the website. Before we use the plugin, we have to import some files. Unfortunately, I coulnt find them online for a direct import, you will have to download them from the tutorial site and add them to your project. The files you need are leaflet-routing-machine.js, leaflet-routing-machine.css and leaflet.routing.icons.png. Be sure to add them to your HTML-file!
Now we can go on and use the plugin in our index.js with the following code:

var map = L.map('map');  
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {  
  attribution: 'Map data © &amp;lt;a href="http://openstreetmap.org"&amp;gt;OpenStreetMap&amp;lt;/a&amp;gt; contributors',  
  maxZoom: 18
}).addTo(map);  
This adds the auto-routing-machine, and also the starting point and end of our route. The points are from the example on Per Liedmans website, the map is now showing Göteborg, with two waypoints that are connected with the shortest route and a description of said route. Note that the way is shown for conventional cars, for other vehicles or for hikig and biking routes you need to modify the L.control object a little bit. The map also has two markers that can be dragged to set a new route, and the possibility to add more waypoints by dragging the route itself. One last thing we want to add is the possibility to click on the map to set the starting point and the end. We can do that with this code:
map.on('click', function (e) {  
  var container = L.DomUtil.create('div'),  
    startBtn = button('Start from this location', container),  
    destBtn = button('End at this location', container);  
  L.DomEvent.on(startBtn, 'click', function () {  
    control.spliceWaypoints(0, 1, e.latlng);  
    map.removeLayer(startmarker);  
    startmarker = new L.marker(e.latlng, {draggable:'true'});  
    startmarker.on('dragend', function(event){  
      startmarker = event.target;  
      var position = startmarker.getLatLng();  
      control.spliceWaypoints(0, 1, position);  
      startmarker.setLatLng(new L.LatLng(position.lat, position.lng),{draggable:'true'});  
    });  
    map.addLayer(startmarker);  
    map.closePopup();  
  });  
  L.DomEvent.on(destBtn, 'click', function () {  
    control.spliceWaypoints(control.getWaypoints().length - 1, 1, e.latlng);  
    map.removeLayer(endmarker);  
    endmarker = new L.marker(e.latlng, {draggable:'true'});  
    endmarker.on('dragend', function(event){  
      endmarker = event.target;  
      var position = endmarker.getLatLng();  
      control.spliceWaypoints(control.getWaypoints().length - 1, 1, position);  
      endmarker.setLatLng(new L.LatLng(position.lat, position.lng),{draggable:'true'});  
    });  
    map.addLayer(endmarker);  
    map.closePopup();  
  });  
  L.popup().setContent(container).setLatLng(e.latlng).openOn(map);  
});  
Now, you can set the start and the end of your route by clicking on the map.

In the end, this is our full code:

index.html:
<!DOCTYPE html>  
<html>  
<head>  
  <meta charset="utf-8" />  
  <title>Leaflet OSRM Example</title>  
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />  
  <link rel="stylesheet" href="leaflet-routing-machine.css"></script>  
</head>  
<body>  
  <div id="map" style="height: 500px; width: 1000px"></div>  
  <script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>  
  <script src="leaflet-routing-machine.js"></script>  
  <script src="index.js"></script>  
</body>  
</html>  

index.js
function button(label, container) {  
   var btn = L.DomUtil.create('button', '', container);  
   btn.setAttribute('type', 'button');  
   btn.innerHTML = label;  
   return btn;  
}  
var map = L.map('map');  
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {  
  attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors',  
  maxZoom: 18,  
}).addTo(map);  
var control = L.Routing.control({  
  waypoints: [  
    L.latLng(57.74, 11.94),  
    L.latLng(57.6792, 11.949)  
  ],  
  routeWhileDragging: false  
}).addTo(map);  
var startBtn;  
var destBtn;  
var startmarker = new L.marker([44.91221, 7.671685], {draggable:'true'});  
var endmarker = new L.marker([44.907852, 7.673789], {draggable:'true'});  
map.on('click', function (e) {  
  var container = L.DomUtil.create('div'),  
    startBtn = button('Start from this location', container),  
    destBtn = button('End at this location', container);  
  L.DomEvent.on(startBtn, 'click', function () {  
    control.spliceWaypoints(0, 1, e.latlng);  
    map.removeLayer(startmarker);  
    startmarker = new L.marker(e.latlng, {draggable:'true'});  
    startmarker.on('dragend', function(event){  
      startmarker = event.target;  
      var position = startmarker.getLatLng();  
      control.spliceWaypoints(0, 1, position);  
      startmarker.setLatLng(new L.LatLng(position.lat, position.lng),{draggable:'true'});  
    });  
    map.addLayer(startmarker);  
    map.closePopup();  
  });  
  L.DomEvent.on(destBtn, 'click', function () {  
    control.spliceWaypoints(control.getWaypoints().length - 1, 1, e.latlng);  
    map.removeLayer(endmarker);  
    endmarker = new L.marker(e.latlng, {draggable:'true'});  
    endmarker.on('dragend', function(event){  
      endmarker = event.target;  
      var position = endmarker.getLatLng();  
      control.spliceWaypoints(control.getWaypoints().length - 1, 1, position);  
      endmarker.setLatLng(new L.LatLng(position.lat, position.lng),{draggable:'true'});  
    });  
    map.addLayer(endmarker);  
    map.closePopup();  
  });  
  L.popup().setContent(container).setLatLng(e.latlng).openOn(map);  
});  
L.Routing.errorControl(control).addTo(map);  
Together with the other files needed, you now have a map with OpenStreetMaps layout, with the possibility to add start and endpoints and waypoints in between, and a router that finds the best route all on its own. Everything is open-source (be sure to check the terms anyways) and free, but working really well. You can add countless other features too, just as you need them, but to show them all would take a lot of time, and there is already a good documentation for anything you might need. Still, I tried to give you an idea of what and how to use the tools, and hope you learned a lot.

Conclusion

Maps and Routing

Conclusion

Now that I have gone through the different ways to show a map on your website, and given you a basic example of how to implement one, I want to finish the blog with a brief conclusion.
I did not invent anything new, nor did I do anything really extraordinary. But I think that having a map on your website can be really useful for many things: whether you use it to show your customers where exactly you are, or to share your favourite hiking route, or whatever you need it for. And as you have seen, you can customise maps really easily, and get really awesome results. Markers, lines and a scrollable map can be a huge upgrade from a static picture of a map. For any type of usage, there is also another solution that fits best, just as i already described in the previous chapters. I hope that my blog could give you an overwiev, so that you already know which solution you will choose when you start, since changing it afterwards can be very time-consuming. I will add all external links I used on the last pages, so if you did not find the link you need in the blog, be sure to check there. This is now the end of my blog, therefore I wish you good luck with implementing your own personal map into a website, and hope everything works fine for you.

Good luck programming,
Lukas Nussbaumer

External links and sources

Here is the list of links and sources I used in and for my blog:

OpenStreetMap:
https://www.openstreetmap.org/

Google Maps:
https://www.google.it/maps

Google Maps license:
http:/www.google.com/permissions/geoguidelines.html

OpenStreetMap license:
http://www.openstreetmap.org/copyright

Google Maps API key:
https://developers.google.com/maps/documentation/javascript 
Google Maps API example 1:
https://developers.google.com/maps/documentation/javascript/examples/map-simple

Google Maps API more examples:
https://developers.google.com/maps/documentation/javascript/examples/?hl=de
Google Maps API example 2:
https://developers.google.com/maps/documentation/javascript/examples/marker-labels

Google Maps API example 3:
https://developers.google.com/maps/documentation/javascript/examples/marker-remove

Google Maps API example 4:
https://developers.google.com/maps/documentation/javascript/examples/polyline-simple

Google Maps API example 5:
https://developers.google.com/maps/documentation/javascript/examples/circle-simple

Leaflet:
http://www.leafletjs.com/

Leaflet documantation:
http://leafletjs.com/reference-1.0.3.html

Leaflet tutorial:
http://leafletjs.com/examples/quick-start/ 
Leaflet routing machine:
http://www.liedman.net/leaflet-routing-machine/tutorials/basic-usage/

These are all the links I used both in my blog, and also to gain the knowledge of how to implement the project myself.

All images without source are either taken from my project or from the example it refers to, in which case I have already added the hyperlink to the respective example.