Show Your Current Location in Map using Navigator Object


Hello Friend’s, Here we will see how to display your current location in map using javascript navigator object. The navigator object contains information about the browser. We need one button control, one label / div or anything to show current co-ordinates that is longitude and latitude and one div tag to show map on page.

So this is my simple HTML code :

<p>Get Location Using Navigator Object</p>
<input id="GetInfo" type="button" value="Click Here To Print Location" />
<p id="Result"></p>
<div id="MapHolderDiv"></div>  

This is the javascript code we are going to use to get current co-ordinates and to create map using google api :

function GetInfo() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(ShowPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function ShowPosition(position) {
    var latlon = position.coords.latitude + "," + position.coords.longitude;
    var x = "<b>Latitude: </b>" + position.coords.latitude +
        "<br><b>Longitude: </b>" + position.coords.longitude;
    document.getElementById("Result").innerHTML = x;
    var img_url = "http://maps.googleapis.com/maps/api/staticmap?center=" + latlon + "&zoom=14&size=400x300&sensor=false";
    document.getElementById("MapHolderDiv").innerHTML = "<img     src='" + img_url + "'>";
}  

Call this Javascript function on button click and you are ready.

Check live Demo here : Show Your Current Location in Map

Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s