This is a code sample taken from the Google Maps API developer’s guide. I’m not super experienced with JavaScript, but I have never seen this syntax before. The portion which confuses me is the first part, where they say “var citymap={};” and then seemingly go on to declare a bunch of citymap keys. Then, later, they say ” for (var city in citymap) {” etc.
Is this the only/the proper method for making a map in JavaScript?
// Create an object containing LatLng, population.
var citymap = {};
citymap['chicago'] = {
center: new google.maps.LatLng(41.878113, -87.629798),
population: 2842518
};
citymap['newyork'] = {
center: new google.maps.LatLng(40.714352, -74.005973),
population: 8143197
};
citymap['losangeles'] = {
center: new google.maps.LatLng(34.052234, -118.243684),
population: 3844829
}
var cityCircle;
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(37.09024, -95.712891),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
for (var city in citymap) {
// Construct the circle for each value in citymap. We scale population by 20.
var populationOptions = {
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: citymap[city].population / 20
};
cityCircle = new google.maps.Circle(populationOptions);
}
}
Let me try to explain each bit of code …
This creates an empty object … the following adds values to the object :
This adds a new key (‘chicago’) and adds some properties to it (
centerandpopulation) the final but which loops the object isthis statement loops the
citymapobject, assigningcityto the key of each object. To access the properties the code usesIts the best way to create and loop and object with multiple values. There is some really good documentation here on working with Objects in JavaScript