I am having a got at a sample I found and can’t figure out what is my issue with the either the Json data format or the way I am trying to read it
The error I am getting is Uncaught TypeError: locations.forEach is not a function
This is how I call my function
showMap
(JSON.stringify({
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-77.034084142948, 38.909671288923]
},
'properties': {
'phoneFormatted': '(202) 234-7336',
'phone': '2022347336',
'address': '1471 P St NW',
'city': 'Washington DC',
'country': 'United States',
'crossStreet': 'at 15th St NW',
'postalCode': '20005',
'state': 'D.C.'
}
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-75.20121216774, 39.954030175164]
},
'properties': {
'phoneFormatted': '(215) 386-1365',
'phone': '2153861365',
'address': '3925 Walnut St',
'city': 'Philadelphia',
'country': 'United States',
'postalCode': '19104',
'state': 'PA'
}
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-77.043959498405, 38.903883387232]
},
'properties': {
'phoneFormatted': '(202) 331-3355',
'phone': '2023313355',
'address': '1901 L St. NW',
'city': 'Washington DC',
'country': 'United States',
'crossStreet': 'at 19th St',
'postalCode': '20036',
'state': 'D.C.'
}
}
]
}));
This is the function I am calling
function showMap(pData)
{
mapboxgl.accessToken = 'pk.eyJ1Ijoic2FtaGVybWVzIiwiYSI6ImNpbGxjeGhmYzVvMm52bm1jdmx0NmtvbXoifQ.uf5gBnnbU05bnaw7atDu9A';
let map = new mapboxgl.Map({
container: 'travel-map',
style: 'mapbox://styles/mapbox/streets-v9',
zoom: 3,
center: [-77.034084142948, 38.909671288923],
scrollZoom: false,
});
var locations = JSON.parse(pData);
var features = Array()
locations.forEach(function (element) {
feature = {
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [element.fields.coordinates.lng, element.fields.coordinates.lat]
},
'properties': {
'title': element.title.rendered,
'visits': element.fields.number_of_visits
}
}
features.push(feature)
})
map.addSource("locations", {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": features
}
})
features.forEach(function (marker) {
var popup = new mapboxgl.Popup()
.setHTML('<div style="padding:0.3rem 0.3rem 0;text-align:center;">'
+ '<h2 style="font-size:16px;margin:0 0 0.3rem;">' + marker.properties.title + '</h2>'
+ '<p style="font-size:12px;margin:0;">Visits: ' + marker.properties.visits + '</p></div>');
new mapboxgl.Marker()
.setLngLat(marker.geometry.coordinates)
.setPopup(popup)
.addTo(map);
});
}