Parsing XML to an array for GMaps API using jQuery
I'm teaching myself javascript by creating my wedding website using the google maps API. I've figured out a lot through the docs and copypasta experimentation, but don't know how to make this happen: what I want to do is read an external XML file containing icon information (names and offsets for a sprite image containing the icons), and store it in an array that I can access when creating m开发者_Go百科ap markers. For example, I want to be able to create a marker for the reception and assign it the icon "party". Here's the code I have so far for reading the icon file:
jQuery.get("markericons.xml", {}, function(data) {
jQuery(data).find("markericon").each(function() {
var icon = jQuery(this);
var name = icon.attr("name");
var url = 'images/icons/mapsprites.png';
var size = new google.maps.Size(32, 37);
var origin = new google.maps.Point(parseInt(icon.attr("x")),parseInt(icon.attr("y")));
var anchor = new google.maps.Point((origin.x+16),origin.y);
var icon = new google.maps.MarkerImage(url, size, origin, anchor);
});
}); // how to store this in an array so that I can access elements by name later?
And then, when creating the actual placemarks on the google map, something like the following:
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: icon.name=="party", // pseudo-code... how to do this?
title: title
});
I'm still a programming noob, so I'd appreciate any help. Thanks!
you should have a JSON object outside of your .each()
or .get()
method, depending on how accessible you want it to be (i'm guessing outside of .get()
, so we'll use that for this example) and then create a JSON object out of your variables inside your .each()
.
var storage = {}
jQuery.get("markericons.xml", {}, function(data) {
jQuery(data).find("markericon").each(function() {
var icon = jQuery(this),
name = icon.attr("name");
storage[name] = {
url: 'images/icons/mapsprites.png',
size: new google.maps.Size(32, 37),
origin: new google.maps.Point(parseInt(icon.attr("x")),parseInt(icon.attr("y"))),
anchor: new google.maps.Point((origin.x+16),origin.y),
icon: new google.maps.MarkerImage(url, size, origin, anchor)
};
});
});
now, you can access your google maps stuff by name:
// for this purpose, let's say `name` is "reception":
console.log(storage.reception)
// => prints out { url: ..., size: ..., origin: ..., anchor: ..., icon: ... }
also, in your original JS, you have icon
declared twice, so I'm not too sure what you want to do with that.
You should use GIcon: http://code.google.com/apis/maps/documentation/javascript/v2/reference.html#GIcon
example how to use it: http://code.google.com/apis/maps/documentation/javascript/v2/examples/icon-simple.html
精彩评论