thecore7
thecore7

Reputation: 484

Setting InfoWindows for markers, with geocoding in a loop

The code below is working. But it isn't using the standard function initialized and that's why I am not able to use online examples to make custom info windows for each address on the map.

How must I define it in order to have it working?

var address = <?php echo json_encode($adr); ?>; //define address array here
var map = new google.maps.Map(document.getElementById('map'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    zoom: 10
});    
var geocoder = new google.maps.Geocoder();
var image = 'http://www.site.com/images/hi.png';
var nbAddresses = address.length;
for (var i=0;i<nbAddresses;i++){
    geocoder.geocode({
        'address': address[i]
    }, 
    function(results, status) {
        if(status == google.maps.GeocoderStatus.OK) {
            new google.maps.Marker({
                position: results[0].geometry.location,
                map: map,
                icon: image,
                title:"Hello"
            });
            map.setCenter(results[0].geometry.location);
        }
    });
}    

Upvotes: 2

Views: 1420

Answers (1)

Shiridish
Shiridish

Reputation: 4962

Here is the Javascript that should do the work

WORKING DEMO

Script:

geocoder.geocode({
        'address': add
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            mark = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map
            });
            map.setCenter(results[0].geometry.location);
            setInfoWindow();
        }
    });

    function setInfoWindow() {
        google.maps.event.addListener(mark, 'click', function(event) {
            var iwindow = new google.maps.InfoWindow();
            iwindow.setContent(event.latLng.lat() + "," + event.latLng.lng());
            iwindow.open(map, this);

        });
    }

Update: Used loops to demonstrate how to assign title value to the maker after Geocoding success-

FIDDLE

The key here is that the loop variable used for fetching addresses isn't available in the scope of the sub function, so you need to create a global variable and increment it to fetch new values from the array for titles.

Upvotes: 2

Related Questions