A
A
Anton Ipatov2019-08-04 01:22:51
Geolocation
Anton Ipatov, 2019-08-04 01:22:51

I'm using Mapbox and want geojson data to be taken from an external source?

I'm using Mapbox, I need the geojson data to be taken from an external source, this is what it looks like now:

<style>
  #map-index { 
    position:absolute;
    z-index:-1;
    left:0;
    top:0;
    bottom:0;
    width:100%;
  }
  .marker {
    display: block;
    border: none;
    border-radius: 50%;
    max-width: 40px;
  	height: auto;
    cursor: pointer;
    padding: 0;
  }
</style>

<div id='map-index'></div>
 
<script>
mapboxgl.accessToken = 'YourAccessToken';

var map = new mapboxgl.Map({
container: 'map-index',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-65.017, -16.457],
zoom: 5
});
 
var geojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"iconImage": 'url(https://res.cloudinary.com/lnky-rocket/image/upload/c_thumb,dpr_3.0,h_100,w_100/v1563358704/rvlbxdokciwuobx2qe4e.jpg)'
},
"geometry": {
"type": "Point",
"coordinates": [
-66.324462890625,
-16.024695711685304
]
}
},
{
"type": "Feature",
"properties": {
"iconImage": 'url(https://res.cloudinary.com/lnky-rocket/image/upload/c_thumb,dpr_3.0,h_100,w_100/v1563358704/rvlbxdokciwuobx2qe4e.jpg)'
},
"geometry": {
"type": "Point",
"coordinates": [
-63.29223632812499,
-18.28151823530889
]
}
}
]
};

// add markers to map
geojson.features.forEach(function(marker) {
// create a DOM element for the marker
var el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage = marker.properties.iconImage;
el.style.backgroundSize = '40px 40px';
el.style.width = '40px';
el.style.height = '40px';
 
el.addEventListener('click', function() {
window.alert(marker.properties.message);
});
 
// add marker to map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.addTo(map);
});
</script>

You need something like this so that the data is taken from an external source
var geojson = {
  data: 'https://gist.githubusercontent.com/ipatovanton/fdc632474dcb331445335d8550b0125d/raw/05d65bf6d688103e0211b2539121cda108ebe5c9/random.geojson';
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2019-08-04
@freeExec

Create a source with the address of your geojson

map.addSource(sourceId, {
                type: "geojson",
                data: 'https://mysite.org/mygejsonfile.geojson'
            });

And then create a layer where the data source will be your newly created source.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question