Reputation: 3797
I have a google map with lots of markers on it (gathered from MySQL database). I'm currently using the following code to change a marker's icon when that marker is clicked:
var redbikeicon = "images/bike_red.png";
<?php
$result=mysql_query("select * from sites") or die(mysql_error());
while($row=mysql_fetch_assoc($result)){
?>
marker = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $row['Latitude']; ?>, <?php echo $row['Longitude']; ?>),
map: map, icon: bikeicon});
//add event to every marker
google.maps.event.addListener(marker, 'click', function(){
//change icon color
this.setIcon(redbikeicon); //replace default icon with red version (color-marking all chosen markers)
})
<?php
}
?>
This code works fine, but I now need to make the same thing happen when a link on the page is clicked - there is a list of links on the page next to the map, and each one corresponds to one of the markers on the map. When a link is clicked, the corresponding marker should change colors just like it does when the marker itself is clicked. How do I accomplish this?
Upvotes: 0
Views: 6615
Reputation: 4568
I do something similar, except I use a hover. I changed it to a click for you below. I am using jQuery for this as well. Anyway, you set up you click event on the link. The link has an attribute called "record_id" which corresponds to a property you set for your marker, also called "record_id".
When the link is clicked, you grab the id, and then iterate through all of your markers until you find the one that matches, and then you change the icon using the setIcon method provided in the googlemaps api.
hope that helps.
setting the id:
marker = new google.maps.Marker({
record_id: record_id,
position: point,
map: map,
title: name,
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=whatever|BDD73C|000000'
});
setting your action on the anchor:
$("a.whatever").click(function(){
var id = $(this).attr('id');
changeMarker(id);
});
using setIcon to swap ut the icon for one of a different color:
function changeMarker(record_id){
for (i in Markers){
if(Markers[i].record_id == record_id){
Markers[i].setIcon('http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=title|EC2A8C|000000');
}
}
}
Upvotes: 8
Reputation: 161384
Trigger the 'click' event on the marker when the link is clicked.
google.maps.event.trigger(gmarkers[i], "click");
example with a clickable dynamic sidebar (the click listener opens an infowindow)
Upvotes: 2