简体   繁体   中英

Using JSON markers in Google Maps API with Javascript

I am quite new to programming, so I'm a little scared to post. But I've been working on something that's likely quite simple for most of you for two days and thought I'd try here...

I am trying to create markers in the Google Maps API.

If I hard code the data into javascript, like this, it works like a charm.

var locations = [
['1 Bedroom House', 55.1111, -100.1111, 1, 'This house has 1 bedroom.'],
['2 Bedroom House', 56.1111, -100.1111, 2, 'This house has 2 bedrooms.'],
['3 Bedroom House', 57.1111, -100.1111, 3, 'This house has 3 bedrooms.'],
['4 Bedroom House', 58.1111, -100.1111, 4, 'This house has 4 bedrooms.']
];

I have a JSON request and need to get the marker data from there instead.

Before you say it, I'm sure I'm WAY off on here... but this is what I got:

var locations = new Array();

$.getJSON("[URL]", function(json) {
        for(var i = 0; i < json.houses.length; i++) {
            var name = json.houses[i].house.name;
            var markerlat = json.houses[i].house.lat;
            var markerlng = json.houses[i].house.lng;
            var description = json.houses[i].house.description;

locations[i] = new Array();
locations[i].push('\'' + name + '\', ' + markerlat + ', ' + markerlng + ', ' + i + ', ' + '\'' + description + '\'');

}
});

Thanks!

By looking at that part of your code, I wonder if it could be solved without the separate locations array.

Could it work if you extend the for loop in the success handler of the $.getJSON function with following kind of code:

new google.maps.Marker({
    position: new google.maps.LatLng(markerlat, markerlng),
    title: name,
    map: [id of the map canvas element]
    });

If you want to have the descriptions also available, you'll have to attach listeners to the markers that trigger info windows. More details of the Info Window overlays and their usage can be found from Google Maps API documentation site .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM