user663724
user663724

Reputation:

How to fetch Data on click of a Marker on google Map

I am dynamically adding Markers to a Google Map on click of a button

The following is the JSON I am sending it from backend .

[
    {
        "longititude": "78.486671",
        "latitude": "17.385044",
        "address": "xxxx",
        "dealerId": "1"
    },

    {
        "longititude": "78.43471",
        "latitude": "17.367044",
        "address": "xxxxSS",
        "dealerId": "2"
    }
]

On click of a button i am calling the following code

My question is on click of a button how can i fetch the dealerId ??

I have got a listener below , how can i fetch the dealer ID ??

 google.maps.event.addListener(global_markers[i], 'click', function() {

                 infowindow.setContent(this['infowindow']);
            infowindow.open(map, this);

        });

function initializeCalllater(lator,lonor,response) {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lator, lonor);
    var myOptions = {
        zoom: 10,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    addMarker(response);
}


function addMarker(markers) {
    if(markers.length>0)
    {
        var infowindow = new google.maps.InfoWindow({});
        var global_markers = [];    

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

        // obtain the attribues of each marker
        var lat = parseFloat(markers[i].latitude);
        var lng = parseFloat(markers[i].longititude);
        var trailhead_name = markers[i].address;
        var dealerId = markers[i].dealerID;

        var myLatlng = new google.maps.LatLng(lat, lng);

        var contentString = "<html><body><div><p><h2>" + trailhead_name + "</h2></p></div></body></html>";

        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: "Coordinates: " + lat + " , " + lng + " | Trailhead name: " + trailhead_name
        });
        marker['infowindow'] = contentString;
        global_markers[i] = marker;
        $(".howmanyfound").text(markers.length + ' Found');
        google.maps.event.addListener(global_markers[i], 'click', function() {
                 infowindow.setContent(this['infowindow']);
            infowindow.open(map, this);

        });
    }
}
}

Could you please let me know how to fetch dealerId on click of a Marker ??

Upvotes: 0

Views: 1001

Answers (1)

geocodezip
geocodezip

Reputation: 161404

You can add dealerId as a property of the google.maps.Marker object (like you did with the InfoWindow contents):

var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: "Coordinates: " + lat + " , " + lng + " | Trailhead name: " + trailhead_name,
    dealerId: dealerId
});

Then in the click function, this.dealerId will give you the value for that marker.

Upvotes: 1

Related Questions