ADD CURRENT GEOLOCATION TO THE GOOGLE MAPS

Posted on

To add current Geolocation, we can use a navigator geolocation

 
navigator.geolocation.getCurrentPosition

We then pass the value to the Maps. Please check this post to see on how we can setup Google Maps to using Latitude and Longitude.

Below is the code and the example on how we can pass the longitude and latitude.

<div id="map"></div>
<script>
var latitude = 3.2544572;
var longitude = 101.7345989;

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}

function showPosition(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
initMap();
}

var map;
function initMap() {
var myLatlng = new google.maps.LatLng(latitude,longitude);
var mapOptions = {
zoom: 16,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);

var marker = new google.maps.Marker({
position: myLatlng,
title:"Google Maps Example!"
});

marker.setMap(map);
}

</script>

For full solution, you can check this example: https://portfolio.adisazizan.xyz/wp-content/uploads/2019/04/google-maps-example-2.html

Please follow and like us:

Leave a Reply

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