Skip to content
Advertisement

How to get current position using html geo location with google maps api

I have this script to display markers on a google map, which works great but now I want to get current position to zoom in on map initially..

<body onload="initCoords()">

function initCoords() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    }
}

function showPosition(position) {
    var lat = position.coords.latitude;
    var long =  position.coords.longitude;
} // this gets the current location loaded when body loads //

How do I pass the lat and long into the map?

    function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: new google.maps.LatLng(lat, long),
      zoom: 12
    });

</body>

It throws lat and long are not defined.

Advertisement

Answer

In the callback showPosition call the setPosition method of the map. As you have declared map within the initMap function perhaps declare the other functions also within the body of initMap

function initMap() {
    lat=56;
    long=-2;
    var map = new google.maps.Map(document.getElementById('map'), {
      center: new google.maps.LatLng(lat, long),
      zoom: 12
    });

    var initCoords=function() {
        if ( navigator.geolocation ) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        }
    }
    var showError=function(e){
        alert(e)
    };

    var showPosition=function( position ) {
        var lat = position.coords.latitude;
        var long =  position.coords.longitude;
        var latlng=new google.maps.LatLng(lat,long);
        map.setPosition( latlng );

        /* add marker?? */
    }


    /* other code ?.... */

}/* close function*/

Or, declare use the callback function to initialise the map

var map,lat,long;

function initMap() {
    var initCoords=function() {
        if ( navigator.geolocation ) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        }
    }
    var showError=function(e){
        alert(e)
    };

    var showPosition=function( position ) {
        var lat = position.coords.latitude;
        var long =  position.coords.longitude;
        var latlng=new google.maps.LatLng(lat,long);

        var map = new google.maps.Map( document.getElementById('map'), {
            center: latlng,
            zoom: 12
        });
    }


    /* other code ?.... */

}/* close function*/
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement