Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  197] [ 4]  / answers: 1 / hits: 21959  / 11 Years ago, wed, august 28, 2013, 12:00:00

I have the following code for placing several markers on a google map.



What I now want to do is when the user clicks on a marker it zooms in and then centers the map to the marker position (this is the bit that's not working - towards the end of the code in the setMarkers function).



Any ideas?



var infowindow = null;
var sites = [];
var partsOfStr = [];
var partsOfStr2 = [];
var bounds;

$(document).ready(function () {
$(select[id*='coordList']).find(option).each(function () {
partsOfStr = $(this).val().split(',');
partsOfStr2 = $(this).text().split('^');
sites.push([partsOfStr2[0], parseFloat(partsOfStr[0]), parseFloat(partsOfStr[1]), partsOfStr[2], partsOfStr2[1], partsOfStr2[2], partsOfStr2[3], partsOfStr[3], partsOfStr[4], partsOfStr[5]]);
});
initialize();
});

function initialize() {
bounds = new google.maps.LatLngBounds();
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(54.57951, -4.41387),
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.HYBRID
}

var map = new google.maps.Map(document.getElementById('map'), mapOptions);

setMarkers(map, sites);

infowindow = new google.maps.InfoWindow({
content: loading...
});

google.maps.event.addListener(infowindow,'closeclick',function(){
map.setCenter(new google.maps.LatLng(54.57951, -4.41387));
map.setZoom(6);
});

}



function setMarkers(map, markers) {

for (var i = 0; i < markers.length; i++) {
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: sites[0],
html: <div class='mapDesc'>content here...</div>
});

google.maps.event.addListener(marker, click, function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
map.setCenter(marker.getPosition()); // NOT WORKING!!!!!!!
map.setZoom(10);
});

bounds.extend(new google.maps.LatLng(sites[1], sites[2]));
map.fitBounds(bounds);
}

}

More From » google-maps

 Answers
13

marker is left pointing to the last marker added. Either use function closure or this like you did for the infowindow:



    google.maps.event.addListener(marker, click, function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
map.setCenter(this.getPosition());
map.setZoom(10);
});

[#76075] Tuesday, August 27, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
paulinap

Total Points: 346
Total Questions: 86
Total Answers: 97

Location: Dominican Republic
Member since Sun, Sep 4, 2022
2 Years ago
;