Reputation: 2508
i am creating a simple location plan, so basically each google map will have a different location with a different marker.
So let's say googlemap2 = coordinate A and googlemap5 = coordinate B, i need each element to have a marker that hits and center in coordinate A and B (separately so that coordinate B marker will never appear in googlemap2 vice versa)
so far my code is as so
var map;
var map2;
function initialize(condition) {
//--------------------------------------------------------------------------- TTDI
if(document.getElementById('googlemap2') !== null){
var map_canvas = document.getElementById('googlemap2');
var myLatlng = new google.maps.LatLng(3.140425, 101.632005);
var mapOptions = {
center: myLatlng,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(map_canvas, mapOptions);
TestMarker(myLatlng, map);
}
//--------------------------------------------------------------------------- CHERAS
if(document.getElementById('googlemap5') !== null){
var map_canvas2 = document.getElementById('googlemap5');
var myLatlng2 = new google.maps.LatLng(3.140425, 99.632004);
var mapOptions2 = {
center: myLatlng2,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map2 = new google.maps.Map(map_canvas2, mapOptions2);
TestMarker(myLatlng2, map2);
}
}
// Testing the addMarker function
function TestMarker(x,y) {
var marker = new google.maps.Marker({
position: x,
map: y
});
}
basically it created what i want, just an annoying part where it always center on the first element, so lets say it centers on coordinate A for googlemap2, googlemap5 will have its marker, but the centering of the map will be off. Any help pls ?
Upvotes: 0
Views: 218
Reputation: 7618
I would do something like the following to accomplish your goal and make the class more flexible.
var Atlas = (function () {
Atlas = function (name) {
this.name = name;
}
Atlas.prototype = {
constructMap: function (options) {
var _this = this;
this.map = new google.maps.Map(options.canvas, options.mapOptions);
},
addMarker: function (center) {
var _this = this;
var marker = new google.maps.Marker({
position: center,
map: _this.map
});
}
}
return Atlas;
})();
var mObj1 = {
canvas: document.getElementById('map1'),
mapOptions: {
center: new google.maps.LatLng(3.140425, 101.632005),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
}
var mObj2 = {
canvas: document.getElementById('map2'),
mapOptions: {
center: new google.maps.LatLng(3.140425, 99.632004),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
}
var atlas = new Atlas("atlas");
atlas.constructMap(mObj1);
atlas.addMarker(mObj1.mapOptions.center);
atlas.constructMap(mObj2);
atlas.addMarker(mObj2.mapOptions.center);
I've made a demo for you here:
Good Luck!
Upvotes: 2