Wednesday, September 21, 2016

Using Google MAPs to show your store locations - Part 2

If you are a beginner, I hope you already have a bit of an idea about how to use Google Map API after reading the previous post.

Let's directly go in to a bit detailed version of how a dynamic ecommerce store locator is developed.
First you need to get the Geolocation of the user. For that you can use the HTML5 navigator.geolocation function.
 navigator.geolocation.getCurrentPosition(showPosition, showDefault, { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 });  

The "showPosition" and "showDefault" are two functions.
- showPosition - get the current location and find the latitude and longitude.
- showDefault - when a user reject sharing the geolocation or if the browser does not support geolocation, we can use this method with predefined latitude and longitude to center the map.

 function getLocation() {  
   if (navigator.geolocation) {  
     var timeoutVal = 10 * 1000 * 1000;  
     navigator.geolocation.getCurrentPosition(showPosition, showDefault, {  
       enableHighAccuracy: true,  
       timeout: timeoutVal,  
       maximumAge: 0  
     });  
   } else {  
     GetLocations(48.864716, 2.349014, 0);  
   }  
 }  
 function showPosition(position) {  
   GetLocations(position.coords.latitude, position.coords.longitude, 0);  
 }  
 function showDefault(error) {  
   GetLocations(48.864716, 2.349014, 0);  
 }  

GetLocations is a function that works with picking up store locations depending on coordinates.

 position.coords.latitude and position.coords.longitude will provide the user's current latitude and longitude. If user block the geolocation, the default is used as Paris city in France. You may choose where ever possible by changing the values.

So, read the links below;

http://www.w3schools.com/html/html5_geolocation.asp
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition

See you in Part 3.

Happy Coding... :)



No comments:

Post a Comment