I am using Leaflet in a React Project, and i want to import a plugin which extends Leaflet Polyline which is Leaflet.Polyline.SnakeAnim
I am not using react-leaflet but directly the Javascript library, here is my code :
import React from 'react';
import L from 'leaflet';
import 'leaflet.polyline.snakeanim';
class LeafletMap extends React.Component {
componentDidMount() {
this.map = L.map('leafletMap', {
center:[0,0],
zoom: 2
});
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(this.map);
let polylinePoints = [
[57.74, 11.94],
[0,0],
[22,22]
];
L.polyline(polylinePoints, {
color: 'blue',
weight: 8
}).addTo(this.map).snakeIn();
}
}
In my IDE, I got a warning on snakeIn() saying the function is unresolved. And the plugin don't work at all.
How can I properly import a Leaflet Plugin into React ?
If you want to trigger the animation when the map loads then place the snake logic inside componentDidMount otherwise save the mapInstance when the map loads and then , using a button, trigger the snake animation inside componentDidUpdate.
class LeafletMap extends React.Component {
state = {
mapInstance: null,
startAnimation: false
};
startSnake = () => this.setState({ startAnimation: true });
componentDidMount() {
const map = L.map("map").setView([51.505, -0.09], 13);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution:
'© OpenStreetMap contributors'
}).addTo(map);
this.setState({ mapInstance: map });
}
componentDidUpdate(prevProps, prevState) {
if (prevState.startAnimation !== this.state.startAnimation) {
const trd = [63.5, 11];
const mad = [40.5, -3.5];
const lnd = [51.5, -0.5];
const ams = [52.3, 4.75];
const vlc = [39.5, -0.5];
const route = L.featureGroup([
L.marker(trd, { icon }),
L.polyline([trd, ams]),
L.marker(ams, { icon }),
L.polyline([ams, lnd]),
L.marker(lnd, { icon }),
L.polyline([lnd, mad]),
L.marker(mad, { icon }),
L.polyline([mad, vlc]),
L.marker(vlc, { icon })
]);
this.state.mapInstance.fitBounds(route.getBounds());
this.state.mapInstance.addLayer(route);
route.snakeIn();
route.on("snakestart snake snakeend", ev => {
console.log(ev.type);
});
}
}
render() {
return (
<>
<div id="map" style={{ height: "90vh" }} />
<button onClick={this.startSnake}>Snake it!</button>
</>
);
}
}
Demo
Related
I am trying to implement a searchbox feature in my react app. But getting this error "Attempted import error: 'MapControl' is not exported from 'react-leaflet'" in the new version of react-leaflet
import { MapContainer, TileLayer, Polygon, Marker, Popup } from 'react-leaflet';
import "./index.css";
// Cordinates of Marcillac
const center = [45.269169177925754, -0.5231516014256281]
const purpleOptions = { color: 'white' }
class MapWrapper extends React.Component {
render() {
return (
<div id="mapid">
<MapContainer center={center} zoom={13} scrollWheelZoom={true}>
<TileLayer
attribution='© OpenStreetMap © CartoDB'
url='https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png'
/>
</MapContainer>
</div>
)
}
}
export default MapWrapper;
The implementation given here https://stackoverflow.com/questions/48290555/react-leaflet-search-box-implementation doesnt work as MapControl is depricted.
Tried 2nd solution as well.
import { Map, useLeaflet } from 'react-leaflet'
import { OpenStreetMapProvider, GeoSearchControl } from 'leaflet-geosearch'
// make new leaflet element
const Search = (props) => {
const { map } = useLeaflet() // access to leaflet map
const { provider } = props
useEffect(() => {
const searchControl = new GeoSearchControl({
provider,
})
map.addControl(searchControl) // this is how you add a control in vanilla leaflet
return () => map.removeControl(searchControl)
}, [props])
return null // don't want anything to show up from this comp
}
export default function Map() {
return (
<Map {...otherProps}>
{...otherChildren}
<Search provider={new OpenStreetMapProvider()} />
</Map>
)
}
Here I get map.addControl is not defined
Your approach is correct. You have just confused react-leaflet versions.
The way you are doing it would be correct in react-leaflet version 2.x
For react-leaflet v.3.x your custom comp should look like this:
function LeafletgeoSearch() {
const map = useMap(); //here use useMap hook
useEffect(() => {
const provider = new OpenStreetMapProvider();
const searchControl = new GeoSearchControl({
provider,
marker: {
icon
}
});
map.addControl(searchControl);
return () => map.removeControl(searchControl)
}, []);
return null;
}
You can take the map reference from useMap hook instead of useLeaflet.
Demo
I have seen solutions where they use the Map component, but I read that this has been updated to the MapContainer which does not have an onClick Method. Right now, my code (below) allows me to add a marker when I click anywhere on the map. As my title states, how would I store the new marker in some kind of usable variable. My end goal is to store new markers in MongoDB. Thanks in advance.
import React, { Component } from 'react';
import {
MapContainer,
TileLayer,
MapConsumer,
} from "react-leaflet";
import Leaflet from "leaflet";
import { connect } from 'react-redux';
import { Icon } from "../Leaflet/Configurations";
import NavBar from '../components/NavBar';
import Footer from '../components/Footer';
import { registerHouse } from '../actions/houseActions';
import { clearErrors } from "../actions/errorActions";
import "leaflet/dist/leaflet.css";
class MyMap extends Component{
constructor(props){
super(props);
this.state = {
markers: [[40.7, -74]],
data: []
};
this.addMarker = this.addMarker.bind(this);
}
render(){
return(
<div>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossOrigin=""/>
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossOrigin=""></script>
<NavBar/>
{/* <MapContainer className="Map" center={{ lat: 40.7 , lng: -74 }} zoom={15} scrollWheelZoom={false}>
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<MapConsumer>
{(map) => {
console.log("map center:", map.getCenter());
map.on("click", function (e) {
const { lat, lng } = e.latlng;
Leaflet.marker([lat, lng], { Icon }).addTo(map);
let tmp = this.state.data;
tmp.append([lat,lng]);
this.setState({data:tmp});
});
return null;
}}
</MapConsumer>
</MapContainer> */}
<Footer/>
</div>
)
}
}
const mapStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated,
error: state.error
});
export default connect(mapStateToProps, { registerHouse, clearErrors })(MyMap);
I am not sure this part of your code works:
let tmp = this.state.data;
tmp.append([lat,lng]);
this.setState({data:tmp});
why? Because this.state is undefined inside map.on('click) block scope. It loses its reference there.
So what you could do is create a custom child component of MapContainer and take advantage of a concept in react called raising an event from the child to the parent component. The parent will send an event to the child and the latter calls that function when something happens.
function MyComponent({ saveMarkers }) {
const map = useMapEvents({
click: (e) => {
const { lat, lng } = e.latlng;
L.marker([lat, lng], { icon }).addTo(map);
saveMarkers([lat, lng]);
}
});
return null;
}
and in your MyMap comp define the event
saveMarkers = (newMarkerCoords) => {
const data = [...this.state.data, newMarkerCoords];
this.setState((prevState) => ({ ...prevState, data }));
};
which will be passed as a prop to the custom comp:
<MapContainer
...
<MyComponent saveMarkers={this.saveMarkers} />
</MapContainer>
Demo
Problem: OpenLayers(v6.3) MAP is visible in REACTJS(16.13) but click event on MAP is not getting called.
Purpose: I want to place a marker and handle its click event to show some POPUP with data.
Code: Code included is though self explanatory; here is a quick explanation
[in ComponentWillUpdate()] MapComponent shown here receive {currentLocation} as property and moves map to that location. It then places a marker with custom Image. Its all working.
[in ComponentDidMount()] DIV ID reference is used to pass OLMAP reference.
I tried to register OLMAP click event in both ComponentDidMount() as well as ComponentWillUpdate() but it is not doing anything though it is getting executed as last console message gets printed.
Only problem in this code is OL-MAP CLICK event Handling. What is wrong. Help will be appreciated.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Feature from 'ol/Feature';
import {Style,Icon} from 'ol/style';
import Point from 'ol/geom/Point';
import { fromLonLat } from 'ol/proj.js';
import LOCPNG from '../../../assets/images/location.png';
class MapComponent extends Component {
constructor(props) {
// console.log('[MC.js] constructor');
super(props);
this.olMap = null;
this.mapRef = null;
this.setMapRef = element => {
this.mapRef = element;
}
}
componentDidUpdate(prevProps, prevState) {
console.log('[MC.js] CDUpdate');
}
componentWillUpdate(nextProps) {
// console.log('[MC.js] CWU');
const mapView = this.olMap.getView();
mapView.animate({
center: nextProps.currentLocation,
duration: 2000,
zoom: 10
});
this.makeMarker(nextProps.currentLocation, 0);
this.olMap.on('click',(evt) => {
console.log(evt);
console.log(evt.pixel);
const feature = this.olMap.forEachFeatureAtPixel(evt.pixel, (feature) => feature);
if(feature){
console.log('PopUp');
}
});
}
makeMarker = (location, index) => {
let marker = new Feature({
geometry: new Point(location)
});
marker.setStyle(new Style({
image: new Icon(({
// crossOrigin: 'anonymous',
src: LOCPNG,
// enter code here`enter code here`
}))
}));
let vectorSource = new VectorSource({ features: [marker] })
var markerVectorLayer = new VectorLayer({
source: vectorSource,
});
this.olMap.addLayer(markerVectorLayer);
}
componentDidMount() {
// console.log('[MC.js] CDM');
const mapDOMNode = ReactDOM.findDOMNode(this.mapRef);
// console.log('[MC.js] CDM',mapDOMNode);
this.olMap = new Map({
target: mapDOMNode,
layers: [
new TileLayer({
source: new OSM()
})
],
view: new View({
center: this.props.currentLocation,
zoom: 10
})
});
this.olMap.on('click',evt=>{
console.log(evt);
console.log(evt.pixel);
const feature = this.olMap.forEachFeatureAtPixel(evt.pixel, (feature) => feature);
if(feature){
console.log('PopUp');
}
});
console.log('[MC.js] CDM');
}
render() {
// console.log('[MC.js] render()');
const styles = { height: '100%', width: '100%' }
return (
<React.Fragment>
<div style={styles} ref={this.setMapRef}></div>
</React.Fragment>
)
}
}
export default MapComponent;
I am trying to change a location in Google Maps API component upon a click on a title in my page file. Can't figure out how to access the component through a different file.
Tried different syntax, "MapContainer.func", MapContainer.props.func".
ContactPage.
import GoogleMaps from '../../../components/GoogleMaps';
import MapContainer from '../../../components/GoogleMaps';
const breadcumbMenu = [
{ name: 'Home', route: '/' },
{ name: 'Contact', },
]
function bkLocation() {
console.log('The bk link was clicked.');
}
function mhLocation() {
console.log('The mh link was clicked.');
//MapContainer.changeLoc(40.712637, -74.008116); <-- need to use changeLoc right here
}
function njLocation() {
console.log('The nj link was clicked.');
}
const ContactPage = () => {
return (.......
GoogleMaps.
import React, { Component } from 'react'
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';
import './style.scss'
const style = {
width: '70%',
height: '100%',
left: '14%'
}
export class MapContainer extends Component {
static defaultProps = {
center: {lat:40.585384,
lng:-73.951200 },
zoom: 11
};
state = {
center: {
lat: 40.7831,
lng: -73.9712
}
}
_changeLoc = (lt, ln) => {
this.setState({
center: {
lat: lt,
lng: ln
}
});};
render() {
return (
<Map
google={this.props.google}
style={style}
zoom={14}
initialCenter={{
lat:40.585384,
lng:-73.951200
}}
center={this.props.center}
>
<Marker onClick={this.onMarkerClick}
name={'Current location'} />
<InfoWindow onClose={this.onInfoWindowClose}>
</InfoWindow>
</Map>
);
}
}
export default GoogleApiWrapper({
apiKey: ("AIzaSyBfumfF_4j5uvjaITGn_VO_pb3O59uu-oE")
})(MapContainer)
The error I am getting is that "changeLoc is not a function / undefined". I need the map api location change when the user clicks on a title (there are 3 titles with the console logs). Somehow I need to connect the changeLoc function and make it callable from the ContactPage file.
Thank you in advance!
you can achieve this the following way
Make _changeLoc static, then you will be able to call MapContainer._changeLoc as you have defined
static _changeLoc = (lt, ln) => {
this.setState({
center: {
lat: lt,
lng: ln
}
});};
option 2 would be to use redux and add the refernece of your function into the redux store
Im using google-maps-react, and it works pretty good, but i just cant understand how can i work with Google Maps API's methods inside my component. Now i need to getBounds of rendered map, but cant find any way to do this. Here is the code, any help would be appreciated.
import React from 'react';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';
const GOOGLE_MAPS_JS_API_KEY='AIzaSyB6whuBhj_notrealkey';
class GoogleMap extends React.Component {
constructor() {
this.state = {
zoom: 13
}
this.onMapClicked = this.onMapClicked.bind(this);
this.test = this.test.bind(this);
}
onMapClicked (props) {
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
})
}
}
test(google) {
// Here i tried a lot of ways to get coords somehow
console.log(google.maps.Map.getBounds())
}
render() {
const {google} = this.props;
if (!this.props.loaded) {
return <div>Loading...</div>
}
return (
<Map className='google-map'
google={google}
onClick={this.onMapClicked}
zoom={this.state.zoom}
onReady={() => this.test(google)}
>
</Map>
);
}
}
export default GoogleApiWrapper({
apiKey: (GOOGLE_MAPS_JS_API_KEY)
})(GoogleMap);
Google Maps Api v 3.30.4
You could try and adapt your requirements to the following example here.
From what i can see a reference is returned using the onReady prop.
For example :
import React from 'react';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';
const GOOGLE_MAPS_JS_API_KEY='AIzaSyB6whuBhj_notrealkey';
class GoogleMap extends React.Component {
constructor() {
this.state = {
zoom: 13
}
this.onMapClicked = this.onMapClicked.bind(this);
this.handleMapMount = this.handleMapMount.bind(this);
}
onMapClicked (props) {
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
})
}
}
handleMapMount(mapProps, map) {
this.map = map;
//log map bounds
console.log(this.map.getBounds());
}
render() {
const {google} = this.props;
if (!this.props.loaded) {
return <div>Loading...</div>
}
return (
<Map className='google-map'
google={google}
onClick={this.onMapClicked}
zoom={this.state.zoom}
onReady={this.handleMapMount}
>
</Map>
);
}
}
export default GoogleApiWrapper({
apiKey: (GOOGLE_MAPS_JS_API_KEY)
})(GoogleMap);