man_or_astroman
man_or_astroman

Reputation: 648

Google maps API watchPosition

Im building a web app in order to show a marker in the users current location using geolocation and GPS. Here is my code

var marker;
 $(window).load(function() {
    myOptions = { zoom: 20, mapTypeId: google.maps.MapTypeId.ROADMAP };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    var watchId = navigator.geolocation.watchPosition(centerMap); 
 });



function centerMap(location)
{
var myLatlng = new google.maps.LatLng(location.coords.latitude,location.coords.longitude);
map.setCenter(myLatlng);
map.setZoom(15);

    $("#lat").text("Latitude : " + location.coords.latitude);
    $("#lon").text("Longitude : " + location.coords.longitude);
    //show current location on map
    marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    zIndex:1
    });

navigator.geolocation.clearWatch(watchId);

 }

This code works but it keep adding markers as the user changes location. How i can show only one marker in the current users location?

Upvotes: 3

Views: 5718

Answers (1)

Johnny
Johnny

Reputation: 7321

Instead of generating a new marker each time centerMap is called simply update its position with marker.setPosition(myLatlng).

Upvotes: 5

Related Questions