Cian W Cian W - 1 month ago 4x
Javascript Question

Add Markers to Google Maps from JS Array

I have the array:

var stops = [];
stops[1] = {name:'One', lat:51.9219465100951 ,long:-8.61797176722262};
stops[2] = {name:'Two', lat:51.9270744 ,long:-8.6105043};
stops[3] = {name:'Three)', lat:51.9254898 ,long:-8.6100269};

I'm trying to loop through and display these markers on a map...

function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 51.933596, lng: -8.578540},
zoom: 14,
mapTypeId: 'hybrid'

for(var i=0; i<=stops.length; i++){
var mypos = {stops[i].lat, stops[i].long};
var marker = new google.maps.Marker({
position: mypos,
map: map,
title: stops[i].name

No markers are being drawn on the map.

I'm getting an unexpected token error of [ on the following line.
var mypos = {stops[i].lat, stops[i].lng};

I've changed this around but still can't get it to work.


mypos needs to be:

var mypos = {lat: stops[i].lat, lng: stops[i].long};

Without "lat:" and "lng:" you're trying to declare an object as if it's an array. 'position' expects either a LatLngLiteral (see above) or a LatLng object, which is declared like this:

var mypos = new google.maps.LatLng(stops[i].lat, stops[i].long};