Website Scripts And Cloud Tutorials

How to Use HTML5 Geolocation Using Google Map

Byadmin

Jun 9, 2016
HTML5 Geolocation API with google maps

Last updated on January 13th, 2022 at 12:57 pm

Click to rate this tutorial!
[Total: 1 Average: 5]

HTML5 Geolocation using google map

In this script we will first identify a user’s geographical position using longitude and latitude from the browser using HTML5 Geolocation API. This is only available in HTML5 navigator.geolocation enabled web browsers. In this script the browser will first confirm with user to approve whether it can share the position with a website or not. Only when a user approves this request our script will work as expected. In HTML5 Geolocation function showPosition() contains those values (Longitude & Latitude). We then pass these values to function mymap() of google maps. From there I am using Geo code reverse functionality of Google Maps to identify the city name from longitude and latitude values. Please note that I am using zoom value of 11 here for the maps. You are free to use any value of your choice. It also displays city name from where your user is accessing the website.

Refer Google Map Documentation For More Code / Details

HTML5 Geolocation API with google maps
HTML5 Geolocation API with google maps


This is how different browsers prompt users about sharing their geolocation.

Microsoft_Edge_share_location_prompt_HTML5
Microsoft Edge share location prompt
mozilla_share_location_prompt_HTML5
Mozilla share location prompt
chrome_share_location_prompt_HTML5
Chrome share location prompt

Go to the next page to see this code in action 🙂


Now let us start with the coding part, HTML has 2 div. I will explain about this later.

<div id="location"></div>
<div id="map"></div>

We have 4 Javascript functions,

getLocation() will check whether browser supports navigator.geolocation function. If it doesn’t then browser will display a message “Geolocation is not supported by this browser”

Else it will call the next function named showPostion() from where it displays Longitude & Latitude inside div which has the ID named as “location”.

Since we now know the Latitude and Longitude we are good to pass it to google map to display the location and that is done by passing values to mymap function like this mymap(lat,lon).

We can also control the size of the map displayed using this style setting in CSS

<style>
      #map {
        width: 100%;
        height: 400px;
      }
    </style>

I am using geocodeLatLng() to show the city name from where your user is accessing the website. Google map will be displayed in the div section with ID named as “map”.

var x = document.getElementById("location");
function getLocation() {
document.getElementById('map').innerHTML = "Loading Map..Please Be Patient.."
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
 
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"
Longitude: " + position.coords.longitude;
var lat = position.coords.latitude;
var lon = position.coords.longitude
document.getElementById("latlng").value = lat+", "+lon;
mymap(lat,lon)
}
function mymap(a,b) {
var myLatLng = {lat: a, lng: b};
 
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: myLatLng
});
 
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'My Location'
});
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
geocodeLatLng(geocoder, map, infowindow);
 
}
 
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}

Last step is to add a button along with the Google Maps API.

<button class="button" onclick="getLocation()">Get Your Location</button>

DEMO

For creating your own API for Maps go to this link.

Note: I am using my own API here. Please make sure that you use yours as without the API this script might not work as expected.

Click to rate this tutorial!
[Total: 1 Average: 5]

Leave a Reply

Your email address will not be published.