Giter Site home page Giter Site logo

react-openlayers's Introduction

react-openlayers

A minimal React wrapper of OpenLayers 3+ written in TypeScript

image

Install

npm install react-openlayers --save-dev

Usage

import {
  interaction, layer, custom, control, //name spaces
  Interactions, Overlays, Controls,     //group
  Map, Layers, Overlay, Util    //objects
} from "react-openlayers";

Example

    <Map view={{center: [0, 0], zoom: 2}} onClick={showPopup}>
      <Layers>
        <layer.Tile/>
        <layer.Vector source={markers} style={markers.style} zIndex="1" />
      </Layers>
      <Overlays>
        <Overlay 
          ref={comp => this.overlayComp = comp}
          element="#popup" />
      </Overlays>
      <Controls attribution={false} zoom={true}>
        <control.Rotate />
        <control.ScaleLine />
        <control.FullScreen />
        <control.OverviewMap />
        <control.ZoomSlider />
        <control.ZoomToExtent />
        <control.Zoom />
      </Controls>
      <Interactions>
        <interaction.Select style={selectedMarkerStyle} />
        <interaction.Draw source={markers} type='Point' />
        <interaction.Modify features={markers.features} />
      </Interactions>
    </Map>

    <custom.Popup ref={comp => this.popupComp = comp}>
    </custom.Popup>

It strictly follows OpenLayers 3+ API documention

About Author

Allen Kim is the creator of ngmap and ng2-map.

If you like this, you may also like geo-coder.

To start

$ git clone https://github.com/allenhwkim/react-openlayers.git
$ cd react-openlayers
$ npm install
$ npm start

List of available npm tasks

  • npm run : List all available tasks
  • npm start: Run app directory for development using webpack-dev-server with port 9001
  • npm run clean: Remove dist folder
  • npm run clean:dist: Clean up unnecessary dist folder within dist and app directory
  • npm run build:umd: Build UMD module react-openlayers.umd.js
  • npm run build:app: Build app/build/app.js for runnable examples
  • npm run build: Build all(build:ngc, build:umc, build:app, and clean:dist)

react-openlayers's People

Contributors

allenhwkim avatar benhurdavies avatar jwgmeligmeyling avatar keithamoss avatar tdesjardins avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-openlayers's Issues

Missing .d.ts

I am aware that I am probably doing something incorrectly, however, when compiling typescript, I am getting the error Could not find a declaration file for module 'react-openlayers'

Steps Taken:
npm install --save react-openlayers

import {
  interaction, layer, custom, control, //name spaces
  Interactions, Overlays, Controls,     //group
  Map, Layers, Overlay, Util    //objects
} from "react-openlayers";

webpack

ms code underlines react-openlayers as an error, as it cannot find the d.ts
If anyone could advise on how to proceed, I would be most appriciative

Use of other map tiles not working

Hi Allen, thanks for your work in this library. I'm trying to use this in a project but I've found some problems. For example I've found there is some problem using other tiles than default. When you create a Map, using react-openlayers as library, it works with no problem.

<Map>
     <Layers>
         <layer.Tile />
     </Layers>
     <Controls attribution={false} zoom={true}></Controls>
</Map>

But if you use different map tile:

<Map>
     <Layers>
         <layer.Tile source={new ol.source.Stamen({ layer: 'watercolor' })} />
     </Layers>
     <Controls attribution={false} zoom={true}></Controls>
</Map>

It doesn’t load the map and you can see an error in the console like this:

Uncaught TypeError: Cannot read property 'D' of null

Thanks for your help

How can i change the view' state of a map after initialization

I am trying to make the view to fit an extent generated from the current features of a vector layer. No matter how i set the new zoom and center, the map won't re-position itself. Can you provide me with details on how to achieve this functionality?
Regards,
Codrin.

How to refresh map after adding new point or line

I want to refresh map when i click on a line.
For example 👍
I have 3 Lines in a map and when i click on 1st line the other two lines will b removed.
i implemented the function but i don't know how i can refresh the map. so it will render again and show new result on map.

draw event not working

there is no example that how i can use drawend event , Below is my code can you please tell me what i am missing, to fire drawend event and want to get latitudes and longitudes of polygon on draw. i will be very thankful to you

import React from 'react';
import Relay from 'react-relay';
import { Row, Col } from 'antd';
import * as ol from 'openlayers';
import {
  interaction, layer, custom, control,
  Interactions, Overlays, Controls,
  Map, Layers, Overlay, Util,
} from 'react-openlayers';

function alert() {
  console.log('hello');
}
const source = new ol.source.Vector();
//draw.on('drawend', alert);
class AccountAreaMap extends React.Component<any,any> {
  overlayComp: any;
  popupComp: any;

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <Row style={ { width: '100%' } }>
        <Col span={ 12 }>
          <Map>
            <Layers>
              <layer.Tile />
              <layer.Vector source={ source } />
            </Layers>
            <Interactions>
              <interaction.Draw source={ source } ondrawend={ () => alert() } type="Polygon" />
            </Interactions>
          </Map>
        </Col>
      </Row>
    );
  }

}

how to use marker event.

I want to use onClick event on marker

import React from 'react';
import * as ol from 'openlayers';

import {
  interaction, layer, custom, control, //name spaces
  Interactions, Overlays, Controls,     //group
  Map, Layers, Overlay, Util    //objects
} from 'react-openlayers';


var iconFeature = new ol.Feature(new ol.geom.Point([0, 0]));
var source = new ol.source.Vector({features: [iconFeature]});
const marker = new custom.style.MarkerStyle();

export default class OverviewMap extends React.Component {
 
 render() {
return(<Map view={ { center: ol.proj.transform([174.78285, -36.93335], 'EPSG:4326', 'EPSG:3857'), zoom: 6 }}>
<Layers>
      <layer.Tile />
         <layer.Vector source={ source } style={ marker.style } />
</Layers>
</Map>);
}
}

Other interactions?

Thank you for this.

Looking at the source code, there isn't any other interactions aside from the default and Select, Draw and Modify. Is this project in active development?

How to change center of map on event?

i am passing new Coordinates in Map component but its not taking me on new centre.

render() {
    console.log(this.props.values.position);
    let view = {};
    view = { center: ol.proj.transform(this.props.values.position, 'EPSG:4326', 'EPSG:3857'), zoom: 8 };
    if (this.props.values.coordinates) {
      const feature = new ol.Feature({
        geometry: new ol.geom.Polygon(this.props.values.coordinates),
      });
      feature.getGeometry().transform('EPSG:4326', 'EPSG:3857');
      feature.setStyle(new ol.style.Style({
        stroke: new ol.style.Style({
          color: '#000000',
          width: 20,
        }),
      }));
      source.clear();
      source.addFeature(feature);
    }
    return (<div style={ { height: '75vh' } }>
      <Map view={ view }>
        <Layers>
          <layer.Tile />
          <layer.Vector source={ source } />
        </Layers>
        <Interactions>
          <interaction.Draw source={ source } type="Polygon" onDrawend={ this.props.onDrawComplete } />
        </Interactions>
      </Map>
    </div>
    );
}

TypeError when using with OpenLayers 4.

Im trying to just follow the basic blueprint of the source files but still getting this error...

Also found this question on stackoverflow

react-openlayers.umd.js:563 Uncaught TypeError: a.V is not a function
    at Hv.k.Nf (react-openlayers.umd.js:563)
    at eh (react-openlayers.umd.js:558)
    at Hv.k.Lf (react-openlayers.umd.js:563)
    at react-openlayers.umd.js:562
    at Array.forEach (<anonymous>)
    at D.k.forEach (react-openlayers.umd.js:460)
    at fh.k.Lf (react-openlayers.umd.js:562)
    at G.k.hp (react-openlayers.umd.js:702)
    at G.<anonymous> (react-openlayers.umd.js:689)

Here is the code...

import React from 'react';
import * as ReactDom from 'react-dom';
import * as ol from 'ol';
import {
  interaction, layer, custom, control, //name spaces
  Interactions, Overlays, Controls,     //group
  Map, Layers, Overlay, Util    //objects
} from "react-openlayers";

// var iconFeature = new ol.Feature(new ol.geom.Point([0, 0]));
// var source = new ol.source.Vector({features: [iconFeature]});
// var marker = new custom.style.MarkerStyle(
//   'https://openlayers.org/en/v4.0.1/examples/data/icon.png'
// );

export default class MapView extends React.Component {
  constructor(props) {
    super(props);
  }

  showPopup = (evt) => {
    this.overlayComp.overlay.setPosition(evt.coordinate);
    var lonlat = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');

    this.popupComp.setContents(
      `<p>You clicked here:</p><code> ${lonlat[0]}, ${lonlat[1]}</code>`
    );
    this.popupComp.show();
  }

  render(){
    debugger;
    return (
      <div>
      <Map onClick={this.showPopup}>
        <Layers>
          <layer.Tile source={new ol.source.Stamen({ layer: 'watercolor' })}/>
        </Layers>
        <Overlays>
          <Overlay ref={comp => this.overlayComp = comp}>
            <custom.Popup ref={comp => this.popupComp = comp}>
            </custom.Popup>
          </Overlay>
        </Overlays>
      </Map>
      </div>
    );
  }
}

I did notice that the ol npm project has a specific way of importing the modules, and its different than this repo imports them, but I have tried both ways and am at a loss.

Here is the package.json if it helps, note I am using create-react-app:

{
  "name": "k51-react",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "ol": "^4.3.4",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-openlayers": "^0.2.1",
    "react-redux": "^5.0.6",
    "react-router-dom": "^4.2.2"
  },
  "devDependencies": {
    "react-scripts": "1.0.13"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Any plans to support OpenLayers 4?

Was looking to use react-openlayers but my coworkers (who have much more OpenLayers experience than I) were encouraging me to use OL4...

(they said OL4 had some features to better limit the resulting webpack javascript bundle size?)

tilewms in source for layer

I wanted to use tilewms to export map from wms servers, but couldn't find a way to do it using this wrapper. Can you please point me to an example for it.

Here is the code which I am looking to rewrite in reactjs:

new ol.layer.Tile({
            source: new ol.source.TileWMS({
                url: wmsurl,
                params: wmsparams
            }),
            isBaseLayer:isBaseLayer,
            opacity: opacity
})

I have tried using:
<layer.Tile source={new ol.source.TileWMS({url:wmsurl})/>

But it gives me error. Also I couldn't pass any additional parameters to it.

[QUESTION] How to set map size?

Hi @allenhwkim , how can I set the size of the map?

It seems to default to { width: "100%", height: "300px" }, with no apparent way to override/set a custom width/height?

Best regards,
André

Dynamic interaction.Draw type

I'm trying to make the type option of interaction.Draw dynamic. My component rerenders, but the type of the interaction does not change.

Centre is not woking on map component

I tried to use centre option of map componenet but its not placing me on new Zealand. Can you please check that if you change centre in your code it worked or not. even i don't like the map default colours , they are dull , how i can change colour of sear and countries just like google maps. Thank you for your support Allen.

  <Map view={ { center: [-36.848461, 174.763336] } }>

fails to npm install due to missing @mapbox/mapbox-gl-style-spec dependency

Hi was looking forward to trying react-openlayers out but it won't npm install due to a missing dependency of the ol-mapbox-style dependency (will file an issue there as well btw but also filing here JIC).

The repo here is now just a placeholder btw:
https://github.com/mapbox/mapbox-gl-style-spec

It says: "This repository has been merged with mapbox-gl-js"

Here's my full install ouput JIC it helps:

npm install react-openlayers --save-dev
npm ERR! Darwin 15.6.0
npm ERR! argv "/Users/dcrus/.nvm/versions/node/v6.10.0/bin/node" "/Users/dcrus/.nvm/versions/node/v6.10.0/bin/npm" "install" "react-openlayers" "--save-dev"
npm ERR! node v6.10.0
npm ERR! npm  v3.10.10
npm ERR! code E404

npm ERR! 404 Not found : @mapbox/mapbox-gl-style-spec
npm ERR! 404 
npm ERR! 404  '@mapbox/mapbox-gl-style-spec' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404 It was specified as a dependency of 'ol-mapbox-style'
npm ERR! 404 
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/dcrus/field-maps-nav/npm-debug.log

heatmap does not overlap on the map

I simply followed along with the example you have published in the /app
But somehow the heatmap layer has a different scale altogether.

At first, the whole heatmap looks like one giant red ball, but if you zoom right in for a while; you shall see the actual heatmap layer, with its details.

At 2 zoom level

maperror

at 15+ zoom level

maperror2

Problems with UMD Build and Webpack

Hey is it possible to generate the js bundle without all the dependencies? The js bundle from react-openlayers ist huge (1.42MB) and includes react+openlayers itself.

If you try things like this with proj4 in a plain es6/jsx project

import { Controls, Layers, Map, control, layer } from 'react-openlayers';

import React from 'react';
import ol from 'openlayers';
import proj4 from 'proj4';

ol.proj.setProj4(proj4);
proj4.defs(EPSG25833, '+proj=utm +zone=33 +ellps=GRS80 +units=m +no_defs');

it's not possible to get it working, because there are two instances of ol defined in the final bundle. Currently I use my own build from your npm package with webpack-node-externals activated. Would be nice if a smaller bundle could be the default - and then setting the peer dependencies (ol, react, ...) in npm package.json itself.

Does not work with React Version > 16.0.0

Hello -

This is the error I get when I try to import the library.

import { Map } from 'react-openlayers'

(TS) Could not find a declaration file for module 'react-openlayers'. '../node_modules/react-openlayers/dist/react-openlayers.umd.js' implicitly has an 'any' type.
Try npm install @types/react-openlayers if it exists or add a new declaration (.d.ts) file containing declare module 'react-openlayers';

Thanks, Shilpi

react-openlayers for react-native

Are there any plans to implement some kind of react-native-openlayers wrapper? I found a Webview-using solution but the implementation is not very user-friendly when it comes to handling custom tiles and markers. stackoverflow question

Thanks!

Unmaintained project? I'm upgrading it!

Hello contributors,

First of all, let me congratulate you for your work on this project! Even if you make proof of modesty by saying it's just a simple wrapper, it remains a great react library that make using OpenLayers with React a real pleasure by its concise syntax!

I'm actually in the need in this exact tool, but can you imagine my face when I tried to add it to my brand new React + Typescript project? Yes, like the pain when you strikes your pinky on a door.
Back to the Github repo, I saw that the last commit was two years ago. Damn, I understand now why it won't work.

But I really want to use it, so I forked it and I'm doing a general upgrade.
Here's my todo-list :

  • Upgrade to React 16.x (Implies migrating to the new Context API) (#36, #37)
  • Upgrade to OpenLayers 4.6.5 (Yes OpenLayers 5 is out but not Typescript ready yet, and typings are stuck to 4.6.5) (#32)
  • Ensure proper management of React Components lifecycles.
  • Make it absolutely type-safe
  • Add missing OpenLayers functionalities
  • Complete the missing examples in the available demo app
  • Resolve some current reported issues, such as #40, #41, etc...
  • Update @types/ol & @types/openlayers packages from DefinitivelyTyped for missing definition of ol/interaction/extent
  • Bonus - Modernise demo app using Material-UI, because I want it to look beautiful ❤️
  • Bonus - Update to the latest version of geo-coder, or write a native one
  • Bonus - Add tests
  • Bonus Upgrade to OpenLayers 5 when typescript ready

Does @allenhwkim or someone else still manage react-openlayers?
I want the original repo staying up to date, so I'll send a PR once I estimate the refactor done, hoping it'll be accepted!
In the case I got no response to the PR, I'm thinking about a complete overhaul once OpenLayers 5 is typescript ready, on a brand new dedicated project, but I hope not!

Thanks for reading!

Vector tiles

Thank you so much for this!

Sorry for being so ignorant: This is probably not the right forum for making feature request, but the final piece of the jigsaw which would make this package perfect in my opinion is inclusion of a vector tile example layer.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.