Google maps - Custom JS to output infowindows and markers issues
Trying to simplify my google maps custom code to put markers and an info bubble. However have run into a few issues which I can't seem to debug the code is below, it's currently outputting nothing. The code defines lat/long/title and content and then trys to ouput them as markers on a map.
<script type="text/jav开发者_如何学Cascript">
function initialize() {
var myLatlng = new google.maps.LatLng(20,0);
var myOptions = {
zoom: 2,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var countries = [
{title:'Afghanistan', lat:34.28, lon:69.11, content:"<h2>Afghanistan</h2><p>16 Alumni</p>"},
{title:'Albania', lat:41.18, lon:19.49, content:"<h2>Albania</h2><p>7 Alumni</p>"},
{title:'Angola', lat:-8.5, lon:13.15, content:"<h2>Angola</h2><p>9 Alumni</p>"},
{title:'Antarctica', lat:-80, lon:0, content:"<h2>Antarctica</h2><p>1 Alumnus</p>"},
{title:'Antigua & Barbuda', lat:17.20, lon:-61.48, content:"<h2>Antigua & Barbuda</h2><p>1 Alumnus</p>"},
{title:'Argentina', lat:-36.30, lon:-60, content:"<h2>Argentina</h2><p>29 Alumni</p>"},
];
for (i=0;i<countries.length;i++)
{
c = countries[i];
marker: new google.maps.Marker({position: new google.maps.LatLng(" + c['lat'] + "," + c['lon'] + "), map: map, title: '" + c['title'] + "'}),
infowindow: new google.maps.InfoWindow({content: '" + c['content'] + "'});
}
var item;
for (var i=0; i<countries.length; i++) {
item = countries[i];
google.maps.event.addListener(item.marker, 'click', makeCallback(item));
}
function makeCallback(country) {
return function () {
country.infowindow.open(map, country.marker);
};
}
}
</script>
There are various typographical and syntax errors in the code. Also there is no need to construct strings in the place of variables. The following is a working version:
...
var countries = [...];
for (var i = 0; i < countries.length; i++) {
var c = countries[i];
c.marker = new google.maps.Marker({
position: new google.maps.LatLng(c.lat, c.lon),
map: map,
title: c.title});
c.infowindow = new google.maps.InfoWindow({content: c.content});
google.maps.event.addListener(c.marker, 'click', makeCallback(c));
}
function makeCallback(country) {
return function () {
country.infowindow.open(map, country.marker);
};
}
精彩评论