Using Maps
Adding, using and adapting geographical maps is a popular requirement that people have when creating web applications… There are different options depending on the developer and user needs/requirements – 2 very common ways are:
- Using the google cloud maps platform
- Using a javascript library like leaflet.js that utilizes OpenStreetMap
The google option requires you to subscribe.As a developer you have a finite number of accesses before google requires you to pay… also you need an API key. OpenStreetMap is free – and using a javascript library like leaflet.js is also free and does not require you to subscribe and/or have an Access key. However: In order to display layers/tiles on your map object – you will need to use something like MapBox – (there are other API’s) which require you to subscribe and offer limited free access.
This semester – one of the CART 351 Technical Presentation will be focused on leaflet.js …
So – here: I will introduce a workflow for accessing and using the Google Maps API – the example will conatin a current API Key (mine) but after the workshop I will regenerate it: so I will show you how to create your own – and eventually – since you will have to sign up – you will then be able to access other Google Cloud Services …
SETUP ::
- You will need to create an account on the Google cloud Platform. There will be a free trial period once you set up – however you are required to enter in your billing information in order to continue…
- Now: the google cloud platform is HUGE – and we will ONLY be accessing the Google Maps API today (but I highy recommend that you investigate the other services offered)…
So once you have signed in you can access the google MAPs API via this link - Enable the MAPS JAVASCRIPT API (our option used today) …
- next – once enabled you will need set up the correct credentials by following the link Credentials in APIs & Services and set up an API key – you should also set up the necessary restrictions for the key … In this case ensure that it can be used with the MAPS JAVASCRIPT API.
- Copy the API key to your clipboard as that is what will be needed in order to run the examples …
- It is good practice to restrict your API key – see here for the following discussion google: using API keys
- Next refer to :https://developers.google.com/maps/documentation/javascript/overview for the official documentation …
- We will do here a set of basic examples
INITIAL HTML
The first step is to create an html page, a div container to hold the map and a load button as well as the initial JS.
Specifically: we load JQUERY (makes our lives easier), and the google Maps API script with my API key included as a query parameter.
Finally, included is a custom script to call the ready() action and an event listener/callback on the button (our intention is to load the map only when the button is clicked) … ).
Once the button is clicked – the map is loaded into the div with its center on Montreal and a zoom level of 8.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | <!DOCTYPE html> <html> <head> <title> Google Map API example </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCZBRj2YVLpdf8BbZDMdfihGrvU8MCXhTk"></script> <script> // we listen for the window load event ... $(document).ready(function(){ let map = null; $('#show-map').on('click',loadAndRun); function loadAndRun(){ console.log("clicked"); let mapProp= { //center on montreal center:new google.maps.LatLng( 45.508888,-73.561668), zoom:8, }; map = new google.maps.Map(document.getElementById("map"),mapProp); } }); </script> </head> <style> /* Always set the map height explicitly to define the size of the div * element that contains the map. */ #wrapper{ height: 600px; width:85%; background:rgba(149, 0, 153,0.55); margin-left:8%; margin-top:10px; padding-top:50px; } #map{ height:550px; } h1{ margin-left:25%; margin-top:5%; color:rgba(149, 0, 153,0.55); font-family: Verdana; } #show-map{ margin-left:25%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } </style> <body> <h1>Initial Google Map Example</h1> <button id="show-map">Show Map</button> <div id = "wrapper"> <div id="map"></div> </div> </body> </html> |
O.K – so if you run the example – you should see an inital map centered on montreal when you click on the button … Note we could make this example much more flexible (i.e. pass the lat/long, zoom as arguments, create multiple maps … ) -> but here we have only gone through a basic setup..
Google Maps – Overlays
Google Maps have several types of overlays:
- Marker: Single locations on a map. Markers can also display custom icon images
- Polyline:Series of straight lines on a map
- Polygon:Series of straight lines on a map, and the shape is “closed”
- Circle and Rectangle
- Info Windows:Displays content within a popup balloon on top of a map
- Custom overlays
FIRST EXAMPLE: ADDING A MARKER:
To add a marker: you need to use the Marker constructor. Note that the position property must be set for the marker to display AND must contain the necessary key value pairs.
You add the marker to the map by using the setMap() method – let’s make a custom function for adding a marker and then call it after creating the map:
1 2 3 4 5 6 | function addMarker(){ let m1Pos = {lat: 45.508888, lng: -73.561668}; let marker = new google.maps.Marker({position: m1Pos}); marker.setMap(map); } |
You need to now add the code to call the function …
We can then modify our marker, i.e. set it to animate when it loads ..
1 | let marker = new google.maps.Marker({position: m1Pos, animation:google.maps.Animation.BOUNCE}); |
We could also set the icon property to have a custom image as opposed to the default marker …
EXAMPLE TWO AND THREE: ADDING PATHS AND FILLED PATHS:
We get specify paths as a sequence of lat/long coordianate position objects and then use the google.maps.Polygon() and the google.maps.Polyline() objects to draw the paths onto the map using the setMap()::
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | function addPath(){ let montreal = {lat: 45.508888, lng: -73.561668}; let sherbrooke = {lat: 45.4042, lng: -71.8929}; let ottawa = {lat:45.4215, lng:-75.6972}; let myTrip = [montreal,sherbrooke,ottawa,montreal]; let flightPath = new google.maps.Polyline({ path:myTrip, strokeColor:"#0000FF", strokeOpacity:0.8, strokeWeight:2 }); flightPath.setMap(map); } function addPolygon(){ let montreal = {lat: 45.508888, lng: -73.561668}; let sherbrooke = {lat: 45.4042, lng: -71.8929}; let ottawa = {lat:45.4215, lng:-75.6972}; let myTrip = [montreal,sherbrooke,ottawa,montreal]; let flightPath = new google.maps.Polygon({ path:myTrip, strokeColor:"#FF0000", strokeOpacity:0.8, strokeWeight:2, fillColor:"#FF0000", fillOpacity:0.8 }); flightPath.setMap(map); } |
These function definitions demonstrate the main properties we need to consider – add to the ready() and then call the functions after creating the map …
EXAMPLE FOUR AND FIVE: REGIONS AND INFO BOXES:
The following two functions will allow one to draw a circular region on the map and/or show a dialog box at a specific marker using the google.maps.Circle() and the google.maps.InfoWindow() objects respectively … Note: to use ALL these objects it is a good idea to always refer to the GOOGLE MAPS API documentation…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | //note: radius measurement is in meters function addCircle(){ let ottawa = {lat:45.4215, lng:-75.6972}; let cityRegion = new google.maps.Circle({ center:ottawa, radius:20000, strokeColor:"#00FF00", strokeOpacity:0.8, strokeWeight:2, fillColor:"#00FF00", fillOpacity:0.4 }); cityRegion.setMap(map); } function addInfoBox(){ let infowindow = new google.maps.InfoWindow({ content:"Hello CART 351!" }); // open at a specific map and marker ... let m1Pos = {lat: 45.508888, lng: -73.561668}; let marker = new google.maps.Marker({position: m1Pos}); marker.setMap(map); infowindow.open(map,marker); } |
Call the functions once the map has been created …
Google Maps – Events
The API also (amongst other stuff) also contains user interface events and error events that you can listen for and handle programmatically…
EXAMPLE ONE:: CLICKING ON A MARKER:
We can add event listeners (i.e. click) on existing markers: the following functions will add one marker + event listener from one position OR the other will do the same from an array of positions::
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <script> // we listen for the window load event ... $(document).ready(function(){ let map = null; $('#show-map').on('click',loadAndRun); function loadAndRun(){ console.log("clicked"); let mapProp= { //center on montreal center:new google.maps.LatLng( 45.508888,-73.561668), zoom:8, }; map = new google.maps.Map(document.getElementById("map"),mapProp); //addAndClickMarker(); let positions = [{lat:45.4215, lng:-75.6972},{lat: 45.4042, lng: -71.8929},{lat: 45.508888, lng: -73.561668}]; addAndClickMarkers(positions); } // A :: function addAndClickMarker(){ // set center and zoom when clicking //let sherbrooke = {lat: 45.4042, lng: -71.8929}; let ottawa = {lat:45.4215, lng:-75.6972}; let marker = new google.maps.Marker({position: ottawa}); marker.setMap(map); google.maps.event.addListener(marker,'click',function() { map.setZoom(9); map.setCenter(marker.getPosition()); }); } // B:: function addAndClickMarkers(arrayOfPositions){ for(let i =0; i< arrayOfPositions.length; i++){ let marker = new google.maps.Marker({position: arrayOfPositions[i]}); marker.setMap(map); google.maps.event.addListener(marker,'click',function() { map.setZoom(9); map.setCenter(marker.getPosition()); }); } } }); </script> |
The above code – replaces the entire ready() …
EXAMPLE TWO:: CLICKING ON THE MAP:
The last example to be shown in this class – is how to dynamically add markers depending on where one clicks on the map …
We need to add an event listener to the map – then the callback involves adding a new marker at that location as well as an event listener on the new marker – where an info box is displayed if you click on the marker…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <script> // we listen for the window load event ... $(document).ready(function(){ let map = null; $('#show-map').on('click',loadAndRun); function loadAndRun(){ console.log("clicked"); let mapProp= { //center on montreal center:new google.maps.LatLng( 45.508888,-73.561668), zoom:8, }; map = new google.maps.Map(document.getElementById("map"),mapProp); // add event listener ... google.maps.event.addListener(map, 'click', function(event) { placeMarker(map, event.latLng); }); } function placeMarker(map, location) { let marker = new google.maps.Marker({ position: location, map: map }); let infowindow = new google.maps.InfoWindow({ content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng() }); //open the window on clicking the marker google.maps.event.addListener(marker, 'click', function() { console.log(marker); //check out the object given back to us:) infowindow.open(map,marker); }); } //end place marker.. }); </script> |
This is really the beginning for dealing with the Google Maps API – please refer to Google Maps JS API for greater in depth examples, explanations and features …