user2987001
user2987001

Reputation: 65

Getting data stored in additional field of googlemap's marker

I'm working with google maps api and javascript which I am not much familiar with. Here's the code I use to draw markers on my map. I get Latitudes and Longitudes from my database:

    var geocoder;
    var map;
    var jsonStr = '<?php echo json_encode($arajka) ?>';
    var LatLong = JSON.parse(jsonStr);
    function initialize() {
        geocoder = new google.maps.Geocoder();
        var mapOptions = {
          center: new google.maps.LatLng(50.000001, 20.000001),
          zoom: 12
        };
        map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
        var marker = [];

        for(var i=0;i<LatLong.length;i++){

           var LatLong1 = new google.maps.LatLng(LatLong[i].lat, LatLong[i].lon);
        marker.ajdi=LatLong[i].id; // storing additional data (I need to get it when user clicks on certain marker)
           marker.push(new google.maps.Marker({position: LatLong1, map: map, title: LatLong[i].login}));

        }
                    // trying to set some listener but it fails.
        google.maps.event.addListener(marker, 'click', function() {
            map.setZoom(8);
            map.setCenter(marker.getPosition());
            alert("ASDASDASD" + marker.ajdi);
        });
    }

So, this listener doesn't work, I don't know why. Well, I expect that it doesn't exactly know what marker is it about. When I tried to do it with a single one, like in tutorial, it worked properly. I don't know what to do when I have this array. Any suggestions please?

Upvotes: 0

Views: 64

Answers (1)

Tomas
Tomas

Reputation: 59575

You have several mistakes in your code:

  1. As @Hollister mentions, marker is an array, so you need to put the addListener call inside the loop;

  2. You have to store the additional marker data into the marker, not into the marker array;

  3. you have to use this in the listener, not marker.

    for(var i=0;i<LatLong.length;i++){
    
       var LatLong1 = new google.maps.LatLng(LatLong[i].lat, LatLong[i].lon);
       var this_marker = new google.maps.Marker({position: LatLong1, map: map, title: LatLong[i].login});
       this_marker.ajdi=LatLong[i].id; // storing additional data (I need to get it when user clicks on certain marker)
       marker.push(this_marker);
    
                // trying to set some listener but it fails.
       google.maps.event.addListener(this_marker, 'click', function() {
           map.setZoom(8);
           map.setCenter(this.getPosition());
           alert("ASDASDASD" + this.ajdi);
       });
    }
    

Upvotes: 2

Related Questions