June 20, 2016 11:16 am

Making the most of the Google Maps API – Keeping the user on the map

Now that we have our map added to the webpage, centered on our desired location, and it takes the entire screen real estate we may want to customize it. Let us say that the application revolves around a particular city. We may want to show where the user is located in that city. For this purpose, we will just add a marker representing the user on the map. We will get the user’s location using HTML5’s Geolocation API and we will refresh his/her location on regular intervals so that his/her location stays updated.  When refreshing, we may want to remove the old marker because the user may already be in a different location and we do not want thousands of markers appearing as the user moves around the map.

Making the most of the Google Maps API – Adding a map

Our initialization function does the following things:

Transporter.init = function () {

Transporter.fetchStops();

setInterval(Transporter.positionUser, 6000);

Transporter.fetchRoutes();

}

It fetches the bus stops and displays them on the map, it fetches the routes of the different transportation vehicles and it positions the user on the map once every 6 seconds.

The method for positioning the user, calls the Gelocation API (navigator.geolocation.getCurrentPosition) and passes a function as argument which accepts the user’s geolocation coordinates.  Inside that callback function that we pass as a parameter, we loop over each marker that positions the user on the map and we remove it from the map using a call to setMapand passing it null after which we delete the user’s previous positioning from the array because we do not want thousands of unused marker positions to be stored in the array (in a different situation, we may actually want this).

ransporter.positionUser = function () { 

navigator.geolocation.getCurrentPosition(function (userGeo) {

for (i = 0; i<Transporter.globals.userMarkers.length;i++) {

Transporter.globals.userMarkers[i].setMap(null);

Transporter.globals.userMarkers.splice(i,1);

}

Thereafter, we add a marker to the Google map with the coordinates returned to us from the Geolocation API/ the anonymous callback function that we passed as a parameter using the google.maps.Marker method. We pass to it an object with options. What we really have to pass is another (position) which pinpoints the latitude/longitude position where the market will be placed and a map property with the map variable returned to us from initializing the Google map using a call to google.maps.Map. We can also add whatever properties we want that will be added to the marker properties for us to use. In our case, we add a title and a description which we will show when the user clicks on the market. We also add an icon property which will customize the marker’s icon with an image that could be located on our server or not (it could be a relative or an absolute path).

varuserMarker = new google.maps.Marker({

position: {

lat: userGeo.coords.latitude,

lng: userGeo.coords.longitude

},

map: map,

title: "I/Me",

description: "I find here / I am located here",

icon: "img/dot-sm.png"

});

Next, when the marker indicating the user’s location is clicked we display a modal which gives some basic information about what it represents. We do this by adding a click event listener, passing it an anonymous function where we  callgoogle.maps.InfoWindow, pass it an object with a content property which contains the HTML code that will be shown in the modal and then we call open on the created window passing it the map where we would like for the window to be shown and the marker which the modal describes.

userMarker.addListener('click', function () {

varinfowindow = new google.maps.InfoWindow({

content: "<p class='text-center lead'><h2>"+userMarker.title+"</h2>"+userMarker.description+"</p>"

});

infowindow.open(map, userMarker);

});

Finally, we add the user-positioning marker to an array so that we can remove it when the new call to the method comes and with it – the new user’s position.

Transporter.globals.userMarkers.push(userMarker);

As a second parameter, the HTML5 Geolocation API allows us to pass a function which will execute when an error occurs (users does not support the API, does not give us permission and such circumstances) and we just alert the possible error.

Transporter.globals.userMarkers.push(userMarker);

},

function (err) {

alert(err);

}

If you want the map to always center on the user’s current location you can just call the setCenter method on your initialized map and pass it the coordinates of the user, like this:

map.setCenter(new google.maps.LatLng(userGeo.coords.latitude, userGeo.coords.longitude));

And that’s it! We have managed to show the user’s position as he traverses our map.

Note that in Firefox, the user would have to tick “Always share location” because otherwise a new request for the user to share his/her location would be given every time setInterval initiates a new call to our function.

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter


Tutorial Categories:

Leave a Reply

Your email address will not be published. Required fields are marked *