I'm trying to recreate a Google Maps heatmap listed on the developer website here. In their example they load multiple latitude/longitude coordinates in an array that is written into the code.
I want to load coordinates from a file. I've searched and seen many examples of this but can't get it to work with this specific heatmap example. I keep getting a "not an Array or MVCArray" error and I feel like I'm missing something simple.
See the loadPoints and getPoints functions below. One is loading from an external file and gives an error. The other loads from the array and works fine.
<script>
var map, heatmap, dataarr;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 37.775, lng: -122.434},
mapTypeId: 'roadmap'
});
heatmap = new google.maps.visualization.HeatmapLayer({
data: loadPoints(), // Gives "not an Array or MVCArray" error, but getPoints() works fine
map: map
});
}
function toggleHeatmap() {
heatmap.setMap(heatmap.getMap() ? null : map);
}
function changeGradient() {
var gradient = [
'rgba(0, 255, 255, 0)',
'rgba(0, 255, 255, 1)',
'rgba(0, 191, 255, 1)',
'rgba(0, 127, 255, 1)',
'rgba(0, 63, 255, 1)',
'rgba(0, 0, 255, 1)',
'rgba(0, 0, 223, 1)',
'rgba(0, 0, 191, 1)',
'rgba(0, 0, 159, 1)',
'rgba(0, 0, 127, 1)',
'rgba(63, 0, 91, 1)',
'rgba(127, 0, 63, 1)',
'rgba(191, 0, 31, 1)',
'rgba(255, 0, 0, 1)'
]
heatmap.set('gradient', heatmap.get('gradient') ? null : gradient);
}
function changeRadius() {
heatmap.set('radius', heatmap.get('radius') ? null : 20);
}
function changeOpacity() {
heatmap.set('opacity', heatmap.get('opacity') ? null : 0.2);
}
function loadJSON(file, callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', file, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
function loadPoints() {
loadJSON("data.php", function(response) {
var data = JSON.parse(response);
dataarr = []
for (i = 0; i < data.length; i++) {
dataarr.push(new google.maps.LatLng(data.lat, data.lon))
}
//return dataarr
console.log(dataarr)
});
}
function getPoints() {
return [
new google.maps.LatLng(37.782551, -122.445368),
new google.maps.LatLng(37.782745, -122.444586),
new google.maps.LatLng(37.782842, -122.443688),
new google.maps.LatLng(37.782919, -122.442815),
new google.maps.LatLng(37.782992, -122.442112),
new google.maps.LatLng(37.783100, -122.441461)
];
}
</script>