Reputation: 2491
I've written the below code and all is working grand from the point of view of data, the data is returned from the ajax call in JSON format like the snippet below.
The problem seems to be with the addMarker
function, the data is passed into the function ok, I've verified this with an alert()
from within the addMarker
function but no markers are being plotted on the map and no errors are being thrown in the browser or console.
Do I need to call setMapOnAll
after each marker is added to display it on the map? I've tried adding setMapOnAll
to the end of the addMarker
function but nothing changed.
JSON:
{id:278, title:"", lat:"52.50474200", lng:"-8.71032700"}
Javascript:
$(document).ready(function () {
var map;
var markers = [];
function loadMap()
{
map = new google.maps.Map(document.getElementById('map_canvas'), {
minZoom: 2,
maxZoom: 12,
zoom: 6,
disableDefaultUI: true,
zoomControl: true
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
} else {
map.setCenter({lat: -34.397, lng: 150.644});
}
loadMarkerData(-1);
}
function addMarker(lat, lng) {
var marker = new google.maps.Marker({
position: {lat: lat, lng: lng},
map: map
});
markers.push(marker);
}
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function loadMarkerData(selectedKeys, year, source)
{
var data = {id: 1};
if (selectedKeys != '' && year != '' && source != '') {
data = {id: 1, selectedKeys:selectedKeys, year:year, source:source};
}
$.ajax(
{
url: "ajaxcall.php",
type: "POST",
data: data,
success: function (data, textStatus, jqXHR)
{
if (data != '') {
markerObj = eval(data);
$.each(markerObj, function(index, element) {
addMarker(element.lat, element.lng)
});
}
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(textStatus);
}
});
}
});
Upvotes: 1
Views: 127
Reputation: 161334
With your original code, I get a javascript error: Assertion failed: InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number
, because those values are strings. You can fix that by changing this:
function addMarker(lat, lng) {
var marker = new google.maps.Marker({
position: {
lat: lat,
lng: lng
},
map: map
});
markers.push(marker);
}
To:
function addMarker(lat, lng) {
var marker = new google.maps.Marker({
position: {
lat: parseFloat(lat),
lng: parseFloat(lng)
},
map: map
});
markers.push(marker);
}
Upvotes: 1