I'm trying to dynamically change a marker layer on my map without requiring that my user reload the page. When users first visit my page they will see a map with some markers representing various locations. I want the user to be able to click a button and have the marker layer change - asynchronously. For example, when they first visit the page it will show them a list of restaurants, but when they click on the "coffee" button, then the marker layer for coffee shops will replace the restaurants marker layer. I have something like the following load when the user first visits my page (it works fine):
var features = [{
type: 'Feature',
properties: {
description: "A Place",
'marker-size': 'large'
},
geometry: {
type: 'Point',
coordinates: [74.12345, 35.12345]
}
...
}];
var geoJson = {
type: 'FeatureCollection',
features: features
};
var geocoder = L.mapbox.geocoder('myname.12345'),
map = L.mapbox.map('map', ''myname.12345')
geocoder.query("New York, NY", showMap);
function showMap(err, data) {
map.fitBounds(data.lbounds);
}
map.featureLayer.setGeoJSON(geoJson);
The function below is supposed to change the featureLayer on my map, but it doesn't work. That is, nothing happens when this function is triggered. What am I doing wrong?
<button type="button" onclick="showNewFeatureLayer()">Coffee Shops</button>
<div id="map"></div> // contains the MapBox map
function showNewFeatureLayer() {
var features = [{
type: 'Feature',
properties: {
description: "Another Place",
'marker-size': 'large'
},
geometry: {
type: 'Point',
coordinates: [74.23456, 35.23456]
}
...
}];
var geoJson = {
type: 'FeatureCollection',
features: features
};
map.featureLayer.setGeoJSON(geoJson);
}
I suspect it may have to do with the fact that MapBox renders the map in an iFrame. However, I've seen other sites asynchronously show different featureLayers, so I know it's possible. I just can't seem to figure it out.