About marker Google API v3?

My idea is using handling click event for map to create markers. Then handling click event for marker to show lat() of this marker. But, it always show lat() of final marker in Array. I can't solved this error. Please help me this problem. Thank all

function addMarker(location){
var goldStar = {
    path: google.maps.SymbolPath.CIRCLE,
    fillColor: "yellow",
    fillOpacity: 0.8,
    scale: 1,
    strokeColor: "gold",
    strokeWeight: 14
};      
mar = new google.maps.Marker({
    position: location,
    animation: google.maps.Animation.DROP,
    icon: goldStar, //or use image
    title: "Hello",
    map: map
});
makerArray.push(mar);
//console.log(makerArray.length);
//click_Marker(mar);
google.maps.event.addListener(mar, 'click', function(){
        alert(mar.getPosition().lat());
});}

function initialize(){
var mapOptions = {
    zoom: 12,
    overviewMapControl: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP,   
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);;
GetCurrentLocation(map);

//Hướng dẫn đi
directionDisplay.setMap(map);
directionDisplay.setPanel(document.getElementById("direction"));

getData();
showListRestaurant();
//Thêm địa điểm vào bản đồ
google.maps.event.addListener(map, 'click', function(event){
        addMarker(event.latLng);    
    });

}

Upvotes: 0

Views: 154

Answers (1)

robasaurus
robasaurus

Reputation: 1032

If that is your complete code then you are missing the var declartion on your mar variable.

mar = new google.maps.Marker({
    position: location,
    animation: google.maps.Animation.DROP,
    icon: goldStar, //or use image
    title: "Hello",
    map: map
});

Should instead have a var at the beginning

var mar = new google.maps.Marker({
    position: location,
    animation: google.maps.Animation.DROP,
    icon: goldStar, //or use image
    title: "Hello",
    map: map
});

This would explain your problem because each marker you are adding is a reference to the same object, therefore every time you add a new click event to mar, you are in fact updating the click event of the same object. The result being that all the click events have the same value.

Here's a working jsfiddle:

http://jsfiddle.net/NGja4/50/

Upvotes: 3

Related Questions