Reputation: 1129
I am using he following js for adding google map, which pulls all my locations from my database within the foreach loop, I want each markers to have a different icon which will be stores in a by field.
Lets say for example I have a field called filename which will store the image path/name (icon.jpg).
I was wondering how I can adapt this script written by August Li to do that.
<script type="text/javascript">
//Sample code written by August Li
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN
}
});
<?php
foreach ($dataProvider->models as $model) {
echo "addMarker({$model->lat}, {$model->lon}, '<b>$model->name</b><br />$model->website');";
}
?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
Upvotes: 1
Views: 156
Reputation:
You would just need a function like:
function makeIcon(filename) {
return new google.maps.MarkerImage(
"http://example.com/path/to/icons/" + filename,
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32)
);
}
updated of course with the path to the location of your icon files.
Then you would need to update the addMarker function to accept an icon parameter:
function addMarker(lat, lng, gicon, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: gicon,
map: map
});
...
Then in your PHP loop, you would need to add the makeIcon() call separately. So, for example,
<?php
foreach ($dataProvider->models as $model) {
echo "gicon = makeIcon(your filename);";
echo "addMarker({$model->lat}, {$model->lon}, gicon, '<b>$model->name</b><br />$model->website');";
}
?>
This echos the code to get the gIcon object based on your filename and then passes it to the modified addMarker.
Upvotes: 2