How can I clean this so that the code handles multiple listings better? I have seen some code examples that pull the marker info from an array, but I can’t seem to get it to work.
The markers need to have “icon:”, “url:” and “title:” attributes. The “icon:” so I can change each markers appearance, the “url:” to point through to the page dedicated to each marker and the “title” just to add the markers name on hover.
I also need the array in the script as I am not gathering it from a database or anything like that.
I am pretty green when it comes to javascript and google maps api, any help would be greatly appreciated.
function createMap(lat, lng, zoomVal) {
var mapOptions = { center: new google.maps.LatLng(lat, lng),
zoom: zoomVal,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var myLatlnglow = new google.maps.LatLng(23.654332,-79.387867);
var markerlow1 = new google.maps.Marker({
position: myLatlnglow,
icon: 'images/map-dot.png',
map: map,
url: '#',
title: 'Name'
});
google.maps.event.addListener(markerlow1, 'click', function() {
window.location.href = markerlow1.url;
});
var myLatlnglow = new google.maps.LatLng(23.688458,-79.300619);
var markerlow = new google.maps.Marker({
position: myLatlnglow,
icon: 'images/map-dot.png',
map: map,
url: '#',
title: 'Name'
});
google.maps.event.addListener(markerlow, 'click', function() {
window.location.href = markerlow.url;
});
}
var map;
function initialize() {
createMap(23.668493, -29.410812,12);
if(navigator.geolocation) {
success = function(position) {
createMap(position.coords.latitude, position.coords.longitude,13);
};
error = function() {
createMap(23.648493, -29.410812,12);
}
navigator.geolocation.getCurrentPosition(success, error);
}
}
If I were you I would make an object of objects for the sake of readability. If you must have efficiency, and want to save space and typing, replace the object with an array and address the data by index (0,1,2…)
Here’s a demo
It should also help later to save the references to the created markers, I’m using the global object
markersand the same IDs.If you later need to change a marker property it is accessible through
markers.