React leaflet marker layer not updating on zoom - reactjs

The react-leaflet-marker-layer does not update on zooming the map in/out.
It stays the same, while the map content changes its zoom level.
This happens both during zoom using mouse scroll and the +/- buttons.
NOTE: This may be related, I noticed the map rendering is very slow and some tiles take very long to load. Zooming in/out helps to load them instantly.
import React from 'react';
import ReactDOM from 'react-dom';
import { Map, Marker, Popup, TileLayer } from 'react-leaflet';
import MarkerLayer from 'react-leaflet-marker-layer';
const position = { lng: -122.673447, lat: 45.522558 };
const markers = [
{
position: { lng: -122.67344700000, lat: 45.522558100000 },
text: 'Voodoo Doughnut',
},
{
position: { lng: -122.67814460000, lat: 45.5225512000000 },
text: 'Bailey\'s Taproom',
},
{
position: { lng: -122.67535700000002, lat: 45.5192743000000 },
text: 'Barista'
},
{
position: { lng: -122.65596570000001, lat: 45.5199148000001 },
text: 'Base Camp Brewing'
}
];
class ExampleMarkerComponent extends React.Component {
render() {
const style = {
border: 'solid 1px lightblue',
backgroundColor: '#333333',
borderRadius: '50%',
marginTop: '-5px',
marginLeft: '-5px',
width: '10px',
height: '10px'
};
return (
<div style={Object.assign({}, this.props.style, style)}></div>
);
}
}
class MapView extends React.Component {
render() {
return (
<div
style={{
height:"700px"
}}>
<Map center={position} zoom={13}
style={{
height:"700px"
}}>
<TileLayer
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
attribution='© OpenStreetMap contributors'
/>
<MarkerLayer
markers={markers}
longitudeExtractor={m => m.position.lng}
latitudeExtractor={m => m.position.lat}
markerComponent={ExampleMarkerComponent} />
</Map>
</div>
);
}
}
module.exports = MapView;

I also encountered this issue. Seems like the developer didn't add some event hadlers dor these casese. Not sure if this was intended, but looks more like a bug. The module version at this moment is 0.0.3, so I would't expect much from it.
You can actually just override the method, that sets the event handlers for the layer.
class MarkerLayer extends MapLayer {
attachEvents () {
const map = this.props.map;
map.on('viewreset', () => this.updatePosition());
map.on('zoom', () => this.updatePosition());
map.on('zoomlevelschange', () => this.updatePosition());
}
}
Now, if you use MarkerLayer class, markers would saty where they belong

Related

How to call a function if Current position within Polygon in google-,maps-react?

I am implementing google-maps-react. I need functinality if user current location is in the polygon, I need to enable a button. I searched for containslocation() but didn't get appropriate answer. Here is my code:
import { Map, GoogleApiWrapper, InfoWindow, Marker, Polygon } from 'google-maps-react';
...
...
<CurrentLocation
centerAroundCurrentLocation
google={this.props.google}
>
<Polygon
paths={triangleCoords}
strokeColor="#0000FF"
strokeOpacity={0.8}
strokeWeight={2}
fillColor="#0000FF"
fillOpacity={0.35} />
<Marker
position={{ lat: this.state.currentPosition.lat, lng: this.state.currentPosition.lng }}
onClick={this.onMarkerClick}
name={'Current Location'}
/>
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
onClose={this.onClose}
>
<div>
<h4>{this.state.selectedPlace.name}</h4>
</div>
</InfoWindow>
</CurrentLocation>
Hereś how you can implement it using google-maps-react library:
You need to have a function everytime the map is ready onReady. This function will fetch the current position.
You can use the HTML5 Geolocation feature to get the current location of the user.
You need to import the useRef from React so that you can use ref to get your polygon object.
Once you have the coordinate of the user and the polygon object, you need to use google.maps.geometry.poly.containsLocation to check if the polygon contains the coordinate.
You need to also import useState to manipulate state variables. You will need this as a flag to determine if the coordinate is contained by the polygon or not and will also be used in the condition when showing the button.
So to show the button html you then use the state variable we set and check if it is set to true, then a button should be shown.
Here's the code snippet for the working code:
import React, { useRef, useState } from "react";
import { Map, GoogleApiWrapper, Polygon } from "google-maps-react";
function MapContainer(props) {
const refPoly = useRef(null);
const style = {
position: "absolute",
width: "400px",
height: "800px"
};
const containerStyle = {
position: "absolute",
width: "800px",
height: "400px"
};
const [showBtn, setShowBtn] = useState(null);
const triangleCoords = [
{ lat: 25.774, lng: -80.19 },
{ lat: 18.466, lng: -66.118 },
{ lat: 32.321, lng: -64.757 }
];
const fetchCurrentPosition = () => {
navigator.geolocation.getCurrentPosition(
function(position) {
var pos = new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
);
console.log(position.coords);
google.maps.geometry.poly.containsLocation(pos, refPoly.current.polygon)
? setShowBtn(true)
: setShowBtn(false);
},
function(error) {
console.log(error);
}
);
};
return (
<div>
{showBtn === true && (
<button display="block" type="button">
Showing Button!
</button>
)}
<div>
<Map
className="map"
style={style}
containerStyle={containerStyle}
google={props.google}
onReady={fetchCurrentPosition}
initialCenter={{
lat: 25.774,
lng: -80.19
}}
style={{ height: "100%", position: "relative", width: "100%" }}
zoom={3}
>
<Polygon
ref={refPoly}
paths={triangleCoords}
strokeColor="#0000FF"
strokeOpacity={0.8}
strokeWeight={2}
fillColor="#0000FF"
fillOpacity={0.35}
/>
</Map>
</div>
</div>
);
}
export default GoogleApiWrapper({
apiKey: "YOUR_API_KEY",
libraries: ["geometry"]
})(MapContainer);
Note: To show the button, change the path value of your polygon around your area so that the condition will be set to true. Also use your own API key to make the code work properly. Here's the working code.

Is there a way to center text inside a polygon in Leaflet?

I have GeoJSON that has names and polygons for every country in the world. I have successfully rendered polygons (which is basically world map) but I don't know how to show names of countries inside each polygon. It would be also nice if I could show names only if they fit inside a polygon based on zoom level. I know i can get polygon center with const center = layer.getBounds().getCenter(); but I just don't know what to do with it. This is my code so far
import React, { Component } from "react";
import { MapContainer, GeoJSON } from "react-leaflet";
import countriesData from "../data/countries.json";
import "leaflet/dist/leaflet.css";
import "./Map.css";
export default class Map extends Component {
onEachCountry = (country, layer) => {
const countryName = country.properties.ADMIN;
layer.on({
mouseover: (e) => {
e.target.setStyle({
color: "red",
});
},
mouseout: (e) => {
e.target.setStyle({
color: "black",
});
},
});
};
render() {
return (
<div>
<MapContainer style={{ height: "80vh" }} center={[0, 0]} zoom={1.5}>
<GeoJSON
style={{
color: "black",
weight: 1,
}}
data={countriesData.features}
onEachFeature={this.onEachCountry}
></GeoJSON>
</MapContainer>
</div>
);
}
}

How to make a moving marker like Uber cars?

I create a marker like this:
import React from "react";
import config from 'config';
import { compose, withProps, withState, lifecycle } from "recompose";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
DirectionsRenderer,
Polyline,
} from "react-google-maps";
const googleApiKey = config.googleApiKey;
const HistoryView = compose(
withProps({
googleMapURL: `https://maps.googleapis.com/maps/api/js?key=${googleApiKey}&v=3.exp&libraries=geometry,drawing,places`,
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `345px` }} />,
mapElement: <div style={{ height: `100%` }} />,
}),
withState('zoom', 'onZoomChange', 11),
withScriptjs,
withGoogleMap,
lifecycle({
componentDidMount() {
const { historyCords } = this.props;
},
componentWillMount() {
this.setState({
zoomToMarkers: map => {
//console.log("Zoom to markers");
const bounds = new google.maps.LatLngBounds();
map.props.children.forEach((child) => {
if (child.type === Marker) {
bounds.extend(new google.maps.LatLng(child.props.position.lat, child.props.position.lng));
}
})
map.fitBounds(bounds);
}
})
},
})
)(props =>
<GoogleMap
//ref={props.zoomToMarkers}
defaultZoom={8}
defaultCenter={new google.maps.LatLng(props.historyCords[0].latitude, props.historyCords[0].longitude)}
center={new google.maps.LatLng(props.latitude, props.longitude)}
zoom={17}
>
{<Polyline path={props.polylineCords}
geodesic={true}
options={{
strokeColor: "#1e9494",
strokeOpacity: 0.75,
strokeWeight: 2,
icons: [
{
icon: "lineSymbol",
offset: "0",
repeat: "20px"
}
]
}}
/>}
{<Marker
options={{icon: {url: "../../public/images/red-mark.svg", scaledSize: new window.google.maps.Size(30, 62)}}}
position={{ lat: props.latitude, lng: props.longitude }}
onClick={props.onMarkerClick} />
}
</GoogleMap>
);
export { HistoryView };
Now how do I move this marker like a car on location updates?
I use states to update the position of the marker but it doesn't animate. How do I do this?
My issue is when a latlng is updated the marker jumps from one place to another but I want it to move like a car. Have you ever tracked an Uber ride on the web? something like that.
Gif for car animation

Why react-google-maps rendering one Circle component twice?

When I added react-google-maps to project, render worked twice. So I have 2 circles one under another. Also, I display the center coordinates by onDragEnd() method. This event works for only one of this circles.
Any others google maps dosen`t exist on project.
Here is some ways I was trying to fix it:
1) Use only withGoogleMap,
2) Use GoogleMapsWrapper component inside render() method of parent component,
3) Use componentDidMount();
trying everything from satckoverflow :)
and nothing helps.
import React, { Component } from 'react';
import MapForm from './mapForm';
import { GoogleMap, withGoogleMap, withScriptjs, Circle } from 'react-google-maps';
const GoogleMapsWrapper = withScriptjs(withGoogleMap(props => {
const {onMapMounted, ...otherProps} = props;
return <GoogleMap {...otherProps} ref={c => {
onMapMounted && onMapMounted(c)
}}>{props.children}</GoogleMap>
}));
class GoogleMapsContainer extends Component {
state = {
coords: {lat:0, lng: 0}
};
dragCircle = () => {
this.setState({
coords: {
lat: this._circle.getCenter().lat(),
lng: this._circle.getCenter().lng()
}
})
}
render() {
return(
<div style={{display: 'flex',flexDirection: 'row', width: '100%', marginLeft: '37px'}}>
<MapForm
filters={this.props.filters}
coords={this.state.coords}
/>
<GoogleMapsWrapper
googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${KEY}&v=3.exp&libraries=geometry,drawing,places`}
loadingElement={<div style={{height: `100%`}}/>}
containerElement={<div style={{position: 'relative',width: '100%', }} />}
mapElement={<div style={{height: `100%`}}/>}
defaultZoom={13}
defaultCenter={KYIV}
>
<Circle
ref={(circle) => {this._circle = circle}}
defaultCenter = {KYIV}
defaultDraggable={true}
defaultEditable={true}
defaultRadius={2000}
onDragEnd = {this.dragCircle}
options={{
strokeColor: `${colors.vividblue}`,
fillColor: `${colors.vividblue}`,
fillOpacity: 0.1
}}
/>
</GoogleMapsWrapper>
</div>
)
}
}
export default GoogleMapsContainer;
I need only one circle with my methods.mycircles
Ok, the problem was in React StrictMode component in project.

google-map-react marker not showing

hi all im trying to implement google maps in react.js , the map is showing fine however when i try to show my marker , nothing is being displayed. IF i remove lat and long values then marker will show up on top of the map. But if i add lat and long values to it , then it stops showing. Can someone please help?
import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
import marker from './marker.png';
import { geolocated } from 'react-geolocated';
const AnyReactComponent = ({ text }) => (
<div>
<img src={marker} style={{ height: '50px', width: '50px' }} />
</div>
);
export default class Map extends Component {
static defaultProps = {
zoom: 11,
};
Componentwillmount() {
console.log(this.props.center.latitude);
}
render() {
return (
<div className="google-map" style={{ width: '100%', height: '2000px', backgroundColor: 'red' }}>
<GoogleMapReact
options={{
styles:ExampleMapStyles
}}
center={this.props.center} defaultZoom={this.props.zoom}>
<AnyReactComponent
lat={59.955413}
lng={30.337844}
text={'Kreyser Avrora'}
/>
</GoogleMapReact>
</div>
);
}
}
The documentation shows that you can use<AnyReactCompenent/> which you can use if you want to have your own Marker or text. However, if you wish to use the default marker then you would have to pass as a property into the <GoogleMapReact></GoogleMapReact> component. The docs mention 'You can access Google Maps map and maps objects by using onGoogleApiLoaded, in this case, you will need to set yesIWantToUseGoogleMapApiInternals to true'. This just means add the name of the property without passing a value to it as I have in mine. It may not be entirely clear from the description in the Readme, but the maps argument is, in fact, the maps API object (and map is, of course, the current Google Map instance). Therefore, you should pass both into the method with the renderMarkers = (map, maps) => {} function.
You can try this:
import React, { Fragment } from 'react';
import GoogleMapReact from 'google-map-react';
const GoogleMaps = ({ latitude, longitude }) => {
const renderMarkers = (map, maps) => {
let marker = new maps.Marker({
position: { lat: latitude, lng: longitude },
map,
title: 'Hello World!'
});
return marker;
};
return (
<Fragment>
<div style={{ height: '50vh', width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: 'YOUR KEY' }}
defaultCenter={{ lat: latitude, lng: longitude }}
defaultZoom={16}
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={({ map, maps }) => renderMarkers(map, maps)}
>
</GoogleMapReact>
</div>
</Fragment>
);
};
export default GoogleMaps;
I think the main question that you need to answer is: What are your center props?
I used your code in sandbox and did a some small adaption: I used the same lat/longitude where your marker should be rendered in order to see at a glance whether it is actually shown. And it is:
https://codesandbox.io/s/00p1ry2v0v
export default class Map extends Component {
static defaultProps = {
zoom: 11,
center: {
lat: 49.955413,
lng: 30.337844
}
};
render() {
const mapStyles = {
width: "100%",
height: "100%"
};
return (
<div
className="google-map"
style={{ width: "100%", height: "2000px", backgroundColor: "red" }}
>
<GoogleMapReact
style={mapStyles}
center={this.props.center}
defaultZoom={this.props.zoom}
>
<AnyReactComponent
lat={49.955413}
lng={30.337844}
text={"Kreyser Avrora"}
/>
</GoogleMapReact>
</div>
);
}
}
So, make sure you start the map with a proper initial center position. :)

Resources