Skip to content

Instantly share code, notes, and snippets.

@martinwairegi
Created Dec 14, 2021
Embed
What would you like to do?
import React, { useState, useRef } from 'react';
import Map from 'ol/Map'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import XYZ from 'ol/source/XYZ'
function MapWrapper(props) {
// state and ref setting logic eliminated for brevity
// initialize map on first render - logic formerly put into componentDidMount
useEffect( () => {
// create and add vector source layer
const initalFeaturesLayer = new VectorLayer({
source: new VectorSource()
})
// create map
const initialMap = new Map({
target: mapElement.current,
layers: [
// USGS Topo
new TileLayer({
source: new XYZ({
url: 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSTopo/MapServer/tile/{z}/{y}/{x}',
})
}),
initalFeaturesLayer
],
view: new View({
projection: 'EPSG:3857',
center: [0, 0],
zoom: 2
}),
controls: []
})
// save map and vector layer references to state
setMap(initialMap)
setFeaturesLayer(initalFeaturesLayer)
},[])
// return/render logic eliminated for brevity
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment