Create React App with OpenLayers v6.x + typescript
Organize Create React App with OpenLayers v6.x + typescript
Create React project /w TypeScript
$ yarn create react-app --typescript
# or
$ npx create-react-app --typescript
Execute project
$ yarn start
OpenLayers initialize
Add OpenLayers package & type definition
$ yarn add ol @types/ol
Modify App.tsx
src/App.tsx
import React from 'react';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
const mapStyle = {
width: "100%",
height: "400px"
}
class App extends React.Component {
componentDidMount() {
new Map({
target: 'map',
layers: [
new TileLayer({
source: new XYZ({
url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'
})
})
],
view: new View({
center: [0, 0],
zoom: 2
})
});
}
render() {
return (
<div className="App">
<div id="map" className="map" style={mapStyle}></div>
</div>
);
}
}
export default App;
- Change App to React Component.
- add
<div id="map" className="map" ></div>
Map will be displayed in the div layer - Import OpenLayers modules
import Map from 'ol/Map'; import View from 'ol/View'; import TileLayer from 'ol/layer/Tile'; import XYZ from 'ol/source/XYZ';
- Declare
componentDidMount()
function and create new Map objectcomponentDidMount() { new Map({ target: 'map', layers: [ new TileLayer({ source: new XYZ({ url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png' }) }) ], view: new View({ center: [0, 0], zoom: 2 }) }); }
- Run build
$ yarn start
Now, you can see like below
Source codes
Used source codes are located below Repository
Comments