Emulate backend features load
by Vladimir Vershinin
HTML
<script src="https://unpkg.com/[email protected]/lodash.js"></script>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v5.3.0/build/ol.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected]/lib/index.umd.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/lib/style.css">
<div id="app">
<div>
<button @click="loadPlaces">Load places</button>
{{ loadingState }}
</div>
<div>
Selected: {{ selectedFeatures }}
</div>
<vl-map data-projection="EPSG:4326">
<vl-view :zoom.sync="zoom" :center.sync="center"></vl-view>
<vl-layer-tile>
<vl-source-osm />
</vl-layer-tile>
<vl-layer-vector id="features" render-mode="image">
<vl-source-vector :features="placeFeatures"></vl-source-vector>
</vl-layer-vector>
<vl-interaction-select :features.sync="selectedFeatures"></vl-interaction-select>
</vl-map>
</div>
CSS
html, body, #app {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
JavaScript
new Vue({
el: '#app',
data () {
return {
zoom: 2,
center: [0, 0],
places: [],
loading: false,
selectedFeatures: [],
}
},
computed: {
loadingState () {
return this.loading ? 'Loading...' : 'Loaded num: ' + this.places.length
},
placeFeatures () {
return this.places.map(place => {
// encode as GeoJSON
return {
type: 'Feature',
id: place.id,
properties: {
address: place.address,
},
geometry: {
type: 'Point',
coordinates: [
place.lon,
place.lat,
],
},
}
})
},
},
methods: {
/**
* Emulates request to the backend API
*/
requestPlacesFromAPI () {
return new Promise(resolve => {
setTimeout(() => {
const places = _.range(0, 100).map(i => {
return {
placeId: 'random-' + i,
address: 'Place Address',
lon: _.random(-50, 50),
lat: _.random(-50, 50),
}
})
resolve(places)
}, 3000)
})
},
loadPlaces () {
this.places = []
this.loading = true
return this.requestPlacesFromAPI().then(places => {
this.places = places
this.loading = false
})
},
},
})