Using JSON Markers in the Google Maps API with Javascript

I am new to programming, so I'm a little afraid to post. But I'm working on something that is probably pretty simple for most of you in two days, and thought I would try here ...

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

If I hardcode the data in 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 you need to get the marker data from here.

Before you say that, I'm sure I am WAY here 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!

+4
source share
1 answer

Having looked at this part of your code, I wonder if it can be solved without a separate array of locations.

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

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

If you want descriptions to be also available, you will need to connect listeners to markers that launch info windows. More information about overlay info windows and their use can be found on the Google Maps documentation site .

0
source

Source: https://habr.com/ru/post/1412112/


All Articles