How do I get the user's current location through the google maps API?

3

I'm new to development with this API and would like to show on the map that I'm developing the user's current position.

My code:

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyB7s0zDs4RMWrpqWjAmr7OD-BQbq8LubZk&amp;sensor=false"></script><script>vargeocoder;varmap;varmarker;functioninitialize(){varlatlng=newgoogle.maps.LatLng(-18.8800397,-47.05878999999999);varoptions={zoom:5,center:latlng,mapTypeId:google.maps.MapTypeId.ROADMAP};map=newgoogle.maps.Map(document.getElementById("mapa"), options);

    geocoder = new google.maps.Geocoder();

    marker = new google.maps.Marker({
        map: map,
        draggable: true,
    });

    marker.setPosition(latlng);
}

  $(document).ready(function () {
    initialize();
});

           

    
asked by anonymous 26.02.2015 / 18:04

1 answer

7

You can use the getCurrentPosition() method of the Geolocation to get the user's current location.

Example based on your code:

var geocoder;
var map;
var marker;

  function initialize() {
    var latlng = new google.maps.LatLng(-18.8800397, -47.05878999999999);
    var options = {
        zoom: 5,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("mapa"), options);

    geocoder = new google.maps.Geocoder();

    marker = new google.maps.Marker({
        map: map,
        draggable: true,
    });

    marker.setPosition(latlng);
}

// verifica se o navegador tem suporte a geolocalização
if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position){ // callback de sucesso
        // ajusta a posição do marker para a localização do usuário
        marker.setPosition(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
    }, 
    function(error){ // callback de erro
       alert('Erro ao obter localização!');
       console.log('Erro ao obter localização.', error);
    });
} else {
    console.log('Navegador não suporta Geolocalização!');
}

$(document).ready(function () {
    initialize();
});

See working in JSFiddle.

    
26.02.2015 / 18:38