Where I am? Geolocation API

With the geolocation api we can know your current position.

first you have to validate if the browser support geolocation.

if(navigator.geolocation) {
//Your browser support geolocation.
 } else {
// Your browser doesn't support geolocation.
 }
 

Then you can get the position, to get the current position you have to call the getCurrentPosition function, this function acepts 3 parameter get position callback, error callback and position options.


navigator.geolocation.getCurrentPosition(getPosition, onError);

function getPosition(position){
alert("Latitude: " + position.coords.latitude + " Longitude: " + position.coords.longitude);

}

function onError(error){
alert("Error: " + error.code + ", " + error.message);
}

Note: geolocation on google chrome browser is restricted to https only.

To get your location on a google map you just need to add the lattitud and the longitud to a google static maps url:

https://maps.googleapis.com/maps/api/staticmap?parameters

like this

https://maps.googleapis.com/maps/api/staticmap?center=40.714728,-73.998672&zoom=14&size=400×300&sensor=false&markers=color:red|40.714728,-73.998672

And to display a Google static map on your html insert the url on the source attribute of a img element.

<img src="http://maps.googleapis.com/maps/api/staticmap?center=40.714728,-73.998672&zoom=14&size=400x300&sensor=false&markers=color:red|40.714728,-73.998672"/>

You can see the complete example on
https://codepen.io/roladh/pen/wGbELy

Leave a comment

Create a website or blog at WordPress.com

Up ↑