Joe C Joe C - 7 months ago 22
Javascript Question

Google Map API not plotting array of markers

I need some advice or a telling off because my code is wrong. I'm new to JQuery and google maps api. I have a JSON get to retrieve my data. I have declared an array and stored (hopefully this is the correct way to do this).

update** - Thanks to @geocodezip I have updated my code to allow correct population of array.

When I run my application the map loads fine but no markers.
I have changed my Google maps initializeMap() to the asynchronous version

function initializeMap() {


var map = new google.maps.Map(document.getElementById("googleMap"), {
zoom: 12,
center: new google.maps.LatLng(citylat, citylng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});


var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < carparksArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(carparksArray[i][1], carparksArray[i][2]),
map: map
});

google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(carparksArray[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}

}


My array in console.log image

I now have an array populated, but still no markers on my map.

This is my whole script. Maybe there are some major flaws.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>



<script type="text/javascript">
//define variables
var geocoder;
var citylat = 0;
var citylng = 0;
var carparksArray = [];

if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position)
{
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}

function errorFunction()
{
alert("Geocoder failed");
}


function initialize()
{
geocoder = new google.maps.Geocoder();
}
//get city of current location and runs codeAddress()
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({ latLng: latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
console.log(results);
$.each(arrAddress, function (i, address_component) {
if (address_component.types[0] == "postal_town") {
itemPostalTown = address_component.address_components[0].long_name;
document.getElementById("town").value = itemPostalTown;
codeAddress();



}
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}



//get latlong of city and runs getCarParks()
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("town").value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {

citylat = results[0].geometry.location.lat();
citylng = results[0].geometry.location.lng();
getCarParksLatLng();

}

else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
//sets map up
function initializeMap() {


var map = new google.maps.Map(document.getElementById("googleMap"), {
zoom: 12,
center: new google.maps.LatLng(citylat, citylng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});


var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < carparksArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(carparksArray[i][1], carparksArray[i][2]),
map: map
});

google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(carparksArray[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}

}
//loads map
function loadScript() {
var script = document.createElement("script");
script.src = "http://maps.googleapis.com/maps/api/js?callback=initializeMap";
document.body.appendChild(script);
}

//get carparks names
function getCarParksLatLng() {

var town = document.getElementById("town").value;
var carparkList = "<p>";

var uri = "http://localhost/api/carparks?$filter=Town%20eq%20%27" + town + "%27";
$.getJSON(uri,
function (data) {
carparksArray = [];
$('#here_data').empty(); // Clear existing text.
// Loop through the list of carparks.
$.each(data, function (key, val) {

carparksArray.push([val.Name, val.Latitude, val.Longitude]);

});
console.log(carparksArray);
});

loadScript();
}
$(document).ready(initialize)

</script>

Answer

You are not adding the entries to the carparkArray correctly. Each array element needs to be an array, so the array looks like this:

var carparksArray = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  // ...
  ];

updated code:

var carparks = [];
$.getJSON(uri,
   function (data) {
     $('#here_data').empty(); // Clear existing text.
     // Loop through the list of carparks.
     $.each(data, function (key, val) {
        carparks.push([val.Name, val.Latitude, val.Longitude]);
     });
   });
  loadScript();
}

proof of concept fiddle