Sunday, December 13, 2015

Get Geo Location with Google Map

Sample code to show how to use the Google Map API for Geo location details.
Code to get your current location (Latitude & Longitude) and how to add the marker on the Google Map.

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (p) {
        var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
        var mapOptions = {
            center: LatLng,
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
        var marker = new google.maps.Marker({
            position: LatLng,
            map: map,
            title: "Your location: Latitude: " + p.coords.latitude + "Longitude: " + p.coords.longitude
        });

        google.maps.event.addListener(marker, "click", function (e) {
            var infoWindow = new google.maps.InfoWindow();
            infoWindow.setContent(marker.title);
            infoWindow.open(map, marker);
        });
    });

else 
{
    alert('Geo Location feature is not supported in this browser.');
}