DarkLeafyGreen
DarkLeafyGreen

Reputation: 70406

Multiple google maps on one page

On one page multiple entities are displayed. For each entity there is a google map. This is how I deal with displaying a map for only one entity:

var map;
var geocoder;

$(document).ready(function(){
    google.maps.event.addDomListener(window, 'load', initialize);
});

function initialize() {
    geocoder = new google.maps.Geocoder();
    var mapOptions = {
        zoom: 16,
        center: new google.maps.LatLng(50.317408,11.12915),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map_canvas'),
        mapOptions);
        codeAddress($('#entityID span#address').text());
}

function codeAddress(address) {

    geocoder.geocode( {
        'address': address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
        } else {
            codeAddress('germany');
        }
    });
}

Now I want to show multiple maps, each with a different location. How would that look like? Any ideas? The algorithm should be able to deal with a dynamic amount of entities.

Upvotes: 3

Views: 5404

Answers (1)

Arthur Halma
Arthur Halma

Reputation: 4001

Create an array of maps, something like this:

var maps = []; // array for now
var geocoder;

$(document).ready(function(){
    google.maps.event.addDomListener(window, 'load', initialize('map_1')); // two calls
    google.maps.event.addDomListener(window, 'load', initialize('map_2'));
});

function initialize(_id) { // Map id for future manipulations
    geocoder = new google.maps.Geocoder();
    var mapOptions = {
        zoom: 16,
        center: new google.maps.LatLng(50.317408,11.12915),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    maps[_id] = new google.maps.Map(document.getElementById('map_canvas_'+_id), // different containers
        mapOptions);
        codeAddress($('#entityID span#address').text());
}

function codeAddress(address, map_id) {

    geocoder.geocode( {
        'address': address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: maps[map_id], // target nedded map by second parametr
                position: results[0].geometry.location
            });
        } else {
            codeAddress('germany');
        }
    });
}

Upvotes: 6

Related Questions