React-Leaflet/React-Routing-Machine: Remove route and waypoints - javascript

I am using the following packages for my map:
"leaflet-routing-machine": "^3.2.12",
"leaflet": "^1.7.1",
"react-leaflet": "^2.7.0",
Essentially I have a Routing machine component which I've integrated with my Map and Markers i.e. (upon clicking two points on the map you get the route) you can drag each and the route updates!
However at this point I have a button which resets everything, clears the markers, the associated LAT & LONG. But I just want the route to reset as well.
You can see those previous routes (in beautiful "chartreuse") stay on the map.
Right now I have a function which is supposed to control when the component is visible:
function clearMarkers(){
setIsRoutingDone(false);
}
{isRoutingDone && <Routing isRoutingDone={isRoutingDone} map={map} myMapRef={myMapRef} icon={{startIcon, endIcon}} userLocation={userLocation} coords={{fromLat, fromLon, toLat, toLon}} />}
This is my Routing Machine:
import { MapLayer } from "react-leaflet";
import L from "leaflet";
import "leaflet-routing-machine";
import { withLeaflet } from "react-leaflet";
class Routing extends MapLayer {
constructor(props) {
super(props);
}
createLeafletElement() {
const { map, coords, icon, removeFrom, removeTo } = this.props;
var dStart = L.latLng(coords.fromLat, coords.fromLon);
var dGoal = L.latLng(coords.toLat, coords.toLon);
this.leafletElement = L.Routing.control({
collapsible: true,
lineOptions: {
styles: [{color: 'chartreuse', opacity: 1, weight: 5}]
},
waypoints: [dStart, dGoal],
createMarker: function(i, waypoints, n) {
if (i === 0) {
marker_icon = icon.startIcon;
}
var marker_icon;
if (i === 0) {
marker_icon = icon.startIcon;
}
else if (i == n - 1) {
marker_icon = icon.endIcon
}
var marker = L.marker(i === 0 ? dStart : dGoal,{
draggable: true,
icon: marker_icon
});
return marker;
}
}).addTo(map.leafletElement);
return this.leafletElement.getPlan();
}
updateLeafletElement(props) {
if(this.leafletElement){
if(this.props.isRoutingDone === false){
this.leafletElement.spliceWaypoints(0, 2); // <-- removes your route
}
}
}
}
export default withLeaflet(Routing);
Actually I logged something in the updateLeafletElement function and zzilch.
And this is my map:
import React, { useState, useEffect, useRef } from 'react'
import { Map, Marker } from 'react-leaflet';
import LocateControl from '../LocateControl/LocateControl.jsx';
import MapboxLayer from '../MapboxLayer/MapboxLayer.jsx';
import Routing from '../RoutingMachine/RoutingMachine.jsx'
export default function MyMap({getAddressFromLatLong, hillfinderFormButtonRef, setCurrentLocation, setCurrentDestination}) {
var myMapRef = useRef();
useEffect(() => {
hillfinderFormButtonRef.current = clearMarkers;
return() => {
hillfinderFormButtonRef.current = null;
}
}, []);
function resetHandler (){
return myMapRef.current();
};
function clearMarkers(){
console.log("markerData ", markerData);
setMarkerData(markerData => [], ...markerData);
setFromLat(fromLat => null);
setFromLon(fromLon => null);
setToLat(toLat => null)
setToLon(toLon => null)
setFrom(from => 0);
setTo(to => 0);
setIsRoutingDone(false);
// setRemoveFrom(removeFrom => null)
// setRemoveTo(removeTo => null)
}
function saveMap(map){
setMap(map);
}
function handleOnLocationFound(e){
setUserLocation(e.latlng)
}
function markerClick(e){
e.originalEvent.view.L.DomEvent.stopPropagation(e)
}
return (
<Map animate={animate} center={userLocation} onClick={setMarkers} onLocationFound={handleOnLocationFound} zoom={zoom} ref={saveMap}>
{markerData && markerData.map((element, index) => {
return (
<Marker
key={index}
marker_index={index}
position={element}
draggable={true}
onClick={markerClick}
onDragend={updateMarker}
icon={element.id === 0 ? startIcon : endIcon}
/>
)
})}
<MapboxLayer
accessToken={MAPBOX_ACCESS_TOKEN}
style="mapbox://styles/mapbox/streets-v9"
/>
<LocateControl startDirectly />
{isRoutingDone && <Routing isRoutingDone={isRoutingDone} map={map} myMapRef={myMapRef} icon={{startIcon, endIcon}} userLocation={userLocation} coords={{fromLat, fromLon, toLat, toLon}} />}
</Map>
)
}
I got rid of the the code that's not important to the problem at hand!
Thanks in advance!

I actually wound up solving it myself!
Think the head scratcher was while react-leaflet has its lifeCycle methods, i.e. createLeaflet, updateLeafletElement you should not forget the regular React life methods!
Not sure if they overlap, but I found adding componentDidMount:
componentDidMount() {
const { map } = this.props;
map.addControl(this.routing);
}
with updateLeafletElement (I'm using the API for the function correctly now) it accepts a fromProps and toProps to just check the value of the prop I pass to the Routing Machine...
updateLeafletElement(fromProps, toProps) {
if (toProps.removeRoutingMachine !== false) {
this.routing.setWaypoints([]);
}
}
Finally on unmount, use the removeControl method on the map you pass into the Routing Machine to remove the Router-Machine!
import { MapLayer } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet-routing-machine';
import { withLeaflet } from 'react-leaflet';
class Routing extends MapLayer {
constructor(props) {
super(props);
}
createLeafletElement(props) {
const { map, coords, icon } = this.props;
var dStart = L.latLng(coords.fromLat, coords.fromLon);
var dGoal = L.latLng(coords.toLat, coords.toLon);
if (map && !this.routing) {
this.routing = L.Routing.control({
collapsible: true,
position: 'bottomleft',
lineOptions: {
styles: [{ color: 'chartreuse', opacity: 1, weight: 5 }]
},
waypoints: [dStart, dGoal],
createMarker: function(i, waypoints, n) {
var marker_icon;
if (i === 0) {
marker_icon = icon.startIcon;
} else if (i == n - 1) {
marker_icon = icon.endIcon;
}
var marker = L.marker(i === 0 ? dStart : dGoal, {
draggable: true,
icon: marker_icon
});
return marker;
}
});
}
return this.routing.getPlan();
}
componentDidMount() {
const { map } = this.props;
console.log('map ', map);
map.addControl(this.routing);
}
updateLeafletElement(fromProps, toProps) {
if (toProps.removeRoutingMachine !== false) {
this.routing.setWaypoints([]);
}
}
componentWillUnmount() {
this.destroyRouting();
}
destroyRouting() {
if (this.props.map) {
this.props.map.removeControl(this.routing);
}
}
}
export default withLeaflet(Routing);
Hope this helps! FYI: this is the app I'm using the Routing Machine in case you'd like to browse the other integrations...

Related

React - Why is componentDidMount event called instantly

I've playing around with animation implemented with reactjs.
In the app I created a car which drives around a track. On this track there are obstacles, which the car should recognize.
I'm using window.setInterval for the repeating events. Maybe this is not the best option, but actually I don't know how to do else.
Since some changes, there are multiple intervals running.
But actually I don't know the reason for it. Can anybody give me a hint, why the racer component is instantly running in componentdidmount event?
The Racer component is giving the current position and degree / ankle to the Track component. The Track component is storing these values in states and giving it to the Racer component as props. But this should not lead to instantly firing componentdidmount event of Racer component, or?
Here is my code:
App.js
import React, { Component } from 'react';
import Track from './components/track.js';
const uuidv1 = require('uuid/v1');
class App extends Component {
constructor(props) {
super(props);
this.state = {
obstacles: [
{
key: uuidv1(),
position: {
left: 500,
top:10,
},
width: 25,
height: 25,
},
{
key: uuidv1(),
position: {
left: 650,
top:60,
},
width: 25,
height: 25,
}
],
};
}
render() {
return (
<div className="App">
<Track width={800} height={100} obstacles={this.state.obstacles}>
</Track>
</div>
);
}
}
export default App;
Track.js
import React, { Component } from 'react';
import styled from 'styled-components';
import Racer from './racer.js';
import Obstacle from './obstacle';
import centralStrip from '../images/centralStrip.png';
const uuidv1 = require('uuid/v1');
class Track extends Component {
constructor(props) {
super(props);
this.state = {
racerCurrentPosition: {
top: 60,
left:150
},
racerDegree: 0,
};
}
componentDidMount() {
}
handleObstacleCheck(position, racerPosition) {
let obstacleFound = false;
obstacleFound = this.props.obstacles.map((obstacle) => {
let returnValue = false;
let obstacleRect = document.getElementById(obstacle.key).getBoundingClientRect();
if( position.right >= obstacleRect.left && position.right <= obstacleRect.right && racerPosition.top >= obstacleRect.top && racerPosition.bottom <= obstacleRect.bottom) {
returnValue = true;
}
return returnValue;
});
let isObstacleFound = false;
if(obstacleFound.indexOf(true) !== -1) {
isObstacleFound = true;
}
return isObstacleFound;
}
handleRacerPositionChange(position) {
this.setState({
racerCurrentPosition: position,
});
}
handleRacerDegreeChange(newDegree) {
this.setState({
racerDegree: newDegree,
});
}
render() {
return (
<TrackImage key={uuidv1()}
id="track"
width={this.props.width}
height={this.props.height}>
<Racer key={uuidv1()}
position={this.state.racerCurrentPosition}
onRacerPositionChange={this.handleRacerPositionChange.bind(this)}
degree={this.state.racerDegree}
onRacerDegreeChange={this.handleRacerDegreeChange.bind(this)}
obstacleFound={this.state.obstacleFound}
trackWidth={this.props.width}
trackHeight={this.props.height}
onObstacleCheck={this.handleObstacleCheck.bind(this)}
/>
{
this.props.obstacles.map((obstacle) => {
return (
<Obstacle key={obstacle.key}
id={obstacle.key}
position={obstacle.position}
width={obstacle.width}
height={obstacle.height}
/>
);
})
}
</TrackImage>
);
}
}
export default Track;
Racer.js
import React, { Component, Fragment } from 'react';
import styled from 'styled-components';
import HelperDistance from './helpers/distance.js';
import HelperCenterCar from './helpers/centerCar.js';
import racerImage from '../images/racer.png';
const uuidv1 = require('uuid/v1');
class Racer extends Component {
constructor(props) {
super(props);
this.state = {
key: uuidv1(),
intervalId: 0,
speed: 0,
helperForLeftPositioning: 0,
helperForTopPositioning: 0,
isMoving: false,
collision: false,
centerOfCarCoordinates: {
x: 25,
y: 12.5
},
obstacleFound: false,
};
this.start = this.start.bind(this);
this.move = this.move.bind(this);
}
componentDidMount() {
if(this.state.intervalId === 0) {
this.start();
}
}
componentWillUnmount() {
window.clearInterval(this.state.intervalId);
}
start() {
this.setState({
speed: 3,
isMoving: true,
}, () => {
this.createInterval();
});
}
stop() {
this.setState({
speed: 0,
isMoving: false,
}, () => {
window.clearInterval(this.state.intervalId);
});
}
move() {
if(this.state.obstacleFound === true) {
let newDegree;
if(this.props.degree === 0) {
newDegree = 360;
}
newDegree--;
this.props.onRacerDegreeChange(newDegree);
}
this.step();
}
step() {
if(this.state.isMoving) {
//...calculate new position
this.setState({
helperForTopPositioning: helperForTopPositioning,
helperForLeftPositioning: helperForLeftPositioning,
},() => {
let position = {
left: positionNewLeft,
top: positionNewTop
};
this.props.onRacerPositionChange(position);
});
}
}
createInterval = () => {
let intervalId = window.setInterval(() => {
this.move();
console.log("IntervalId: " + intervalId);
},100);
this.setState({
intervalId: intervalId,
})
}
handleDistanceChange(position) {
let racerRect = document.getElementById(this.state.key).getBoundingClientRect();
let obstacleFound = this.props.onObstacleCheck(position, racerRect);
if(this.state.obstacleFound !== obstacleFound) {
this.setState({
obstacleFound: obstacleFound
});
}
}
render() {
return (
<Fragment>
<Car key={this.state.key} id={this.state.key} position={this.props.position} degree={this.props.degree}>
<HelperCenterCar key={uuidv1()} position={this.state.centerOfCarCoordinates} degree={this.props.degree} />
<HelperDistance key={uuidv1()} onChange={this.handleDistanceChange.bind(this)} position={this.state.centerOfCarCoordinates} degree={this.props.degree} />
</Car>
</Fragment>
);
}
}
export default Racer;
The HelperCenterCar and HelperDistance are components, which helps to identify, if there is an obstacle in the way. I'll post just the code of HelperDistance, because here instantly state updates are fired.
HelperDistance.js
import React, { Component } from 'react';
import styled from 'styled-components';
const uuidv1 = require('uuid/v1');
class HelperDistance extends Component {
constructor(props) {
super(props);
this.state = {
key: uuidv1(),
};
}
componentDidMount() {
this.handleOnChange();
}
componentDidUpdate(prevProps, prevState, snapshot) {
this.handleOnChange();
}
handleOnChange() {
let position = document.getElementById(this.state.key).getBoundingClientRect();
this.props.onChange(position);
}
render() {
return (
<Line id={this.state.key} key={this.state.key} position={this.props.position} degree={this.props.degree} />
);
}
}
export default HelperDistance;

How do I change state in reducer from a click in my component?

I am working on a collaborative project, I wanted to know if I could change the state in my reducer by an onClick event listener or anything in my component.
const defaultState = {
pending: false,
error: null,
trips: {},
activeTrip: null,
privacy: false
}
export const tripReducer = (state = defaultState, action) => {
switch (action.type) {
case TOGGLE_VISIBILITY_ON:
return {
...state,
visibility: true,
}
case TOGGLE_VISIBILITY_OFF:
return {
...state,
visibility: false,
}
}
These are the cases that I am concerned with atm. So I want to change visibility once a person marks their trip public in the activepanel component.
code for activePanel
import React from "react"
import * as s from "./components"
import { connect } from "react-redux"
import moment from "moment"
import PropTypes from "prop-types"
import { TripPropTypes } from "../../propTypes"
import { Button } from "../../../styles/theme/styledComponents"
import { toggleWaypoint } from "../../../redux/actions/trips"
import marker from "../../icons/orange-marker.svg"
import startMarker from "../../icons/green-marker.svg"
import endMarker from "../../icons/black-marker.svg"
import { Link } from "react-router-dom"
class ActiveTripPanel extends React.Component {
constructor(props) {
super(props)
this.state = {
polylines: null,
markers: []
}
}
componentDidMount() {
setTimeout(() => {
this.renderWaypoints()
this.drawPolylines()
}, 500)
}
componentDidUpdate(prevProps) {
if (prevProps.waypoints !== this.props.waypoints) {
this.renderWaypoints()
this.drawPolylines()
}
}
drawPolylines = () => {
if (this.state.polylines !== null) {
this.state.polylines.active.setMap(null)
this.state.polylines.complete.setMap(null)
this.state.polylines.current.setMap(null)
}
let completeIndex = 0
for (let i = 0; i < this.props.waypoints.length; i++) {
if (!this.props.waypoints[i].complete) {
completeIndex = i
break
}
}
const completed = this.props.waypoints.slice(0, completeIndex)
const active = this.props.waypoints.slice(
completeIndex,
this.props.waypoints.length + 1
)
const current = this.props.waypoints.slice(
completeIndex - 1,
completeIndex + 2
)
const completePath = completed.map(waypoint => {
return { lat: waypoint.lat, lng: waypoint.lon }
})
const activePath = active.map(waypoint => {
return { lat: waypoint.lat, lng: waypoint.lon }
})
const currentPath = current.map(waypoint => {
return { lat: waypoint.lat, lng: waypoint.lon }
})
const completePolyline = new window.google.maps.Polyline({
path: completePath,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
})
const currentPolyline = new window.google.maps.Polyline({
path: currentPath,
strokeColor: "#008000",
stokeOpacity: 1.0,
stokeWeight: 2
})
const activePolyline = new window.google.maps.Polyline({
path: activePath,
strokeColor: "#000000",
strokeOpacity: 1.0,
strokeWeight: 2
})
completePolyline.setMap(window.map)
activePolyline.setMap(window.map)
currentPolyline.setMap(window.map)
this.setState({
polylines: {
active: activePolyline,
complete: completePolyline,
current: currentPolyline
}
})
}
renderWaypoints = () => {
let markers = []
const baseIcon = {
anchor: new window.google.maps.Point(15, 30),
scaledSize: new window.google.maps.Size(30, 30),
labelOrigin: new window.google.maps.Point(15, 13)
}
const icons = {
start: {
url: startMarker,
...baseIcon
},
end: {
url: endMarker,
...baseIcon
},
marker: {
url: marker,
...baseIcon
}
}
this.props.waypoints.map((item, i) => {
const icon =
i === 0
? icons.start
: i === this.props.waypoints.length - 1
? icons.end
: icons.marker
let center = { lat: item.lat, lng: item.lon }
const marker = new window.google.maps.Marker({
position: center,
map: window.map,
icon,
title: item.name,
label: {
text: `${i + 1}`,
color: "white",
fontFamily: "Wals",
fontWeight: "bold"
}
})
markers.push(marker)
})
}
render() {
// console.log(match.params.tripId)
// const publicId = ({ match })
return (
<s.Panel>
{/* <s.PanelHeader>{this.props.trip.name}</s.PanelHeader>
<s.DateLabel>
Start: {moment(this.props.trip.start).format("YYYY-MM-DD")} - End:{" "}
{moment(this.props.trip.end).format("YYYY-MM-DD")}
</s.DateLabel> */}
<Link to={`/public/${this.props.trip.id}`}>Share Trip</Link>
<s.WaypointTracker>
{this.props.waypoints &&
this.props.waypoints.map(waypoint => (
<s.WaypointStepper key={waypoint.id}>
<div>
<h4>{waypoint.name}</h4>
<div>
ETA: {moment(waypoint.start).format("YYYY-MM-DD HH:mm")}
</div>
<div>
Status: Checked In #{" "}
{moment(waypoint.start).format("HH:mm")}
</div>
</div>
<div>
{waypoint.complete ? (
<Button
onClick={() => this.props.toggleWaypoint(waypoint.id)}
>
<i className="fa fa-check" />
</Button>
) : (
<Button
onClick={() => this.props.toggleWaypoint(waypoint.id)}
>
<i className="fa fa-times" />
</Button>
)}
</div>
</s.WaypointStepper>
))}
</s.WaypointTracker>
</s.Panel>
)
}
}
ActiveTripPanel.propTypes = {
trip: TripPropTypes,
waypoints: PropTypes.array.isRequired,
toggleWaypoint: PropTypes.func.isRequired
}
const mapStateToProps = ({ trips }) => ({
trip: trips.activeTrip,
waypoints: trips.activeTrip && trips.activeTrip.waypoints,
visibility: trips.visibility
})
export default connect(
mapStateToProps,
{ toggleWaypoint }
)(ActiveTripPanel)
I want to know if its possible or if theres another way to go about it. I am novice at redux. Thank you for the help.
I read the question's text, not the code (long... :)
It is very common (probably the most common way) to change the reducer's state following an event (e.g. onClick):
the onClick event calls an action creator
The action creator returns an action
The action is handled by the reducer
The reducer changes the state.
Does this make sense? I am not sure I understand your question, since this is a standard flow in redux.
BTW, you might want to read an excellent article which helped me when I started learning redux: https://www.sohamkamani.com/blog/2017/03/31/react-redux-connect-explained/

Sharing State Between Components

I want to make two components: App and Map. However when I try to make a new brand Map component and send the data from App to Map component, I cannot.
My App (default) component holds the data as a state. When I try to send this state to the Map component. It holds the data as a prop.
And of course If I don't separate them and write everything in App.js, everything works as I expected (markers shown on the map). But I want to control all states in the parent component.
Am I violating a fundamental React rule? How can I fix that?
App.js
import React, { Component } from "react";
import "./App.css";
import Map from "./Map";
class App extends Component {
constructor(props) {
super(props);
this.state = {
locations: [],
markers: []
};
}
componentDidMount() {
fetch(
"correct_foursquare_api_url"
)
.then(response => response.json())
.then(data =>
data.response.venues.map(place => ({
id: place.id,
name: place.name,
lat: place.location.lat,
lng: place.location.lng
}))
)
.then(locations => {
this.setState({ locations });
});
}
render() {
return (
<div className="App">
<Map locations={this.state.locations} />
</div>
)
}
}
export default App;
Map.js
import React, { Component } from "react";
/* global google */
class Map extends Component {
constructor(props) {
super(props);
this.state = {
locations: [],
markers: []
};
}
componentDidMount() {
this.callMap();
}
callMap() {
window.initMap = this.initMap;
loadJS(
"api_url"
);
}
// Map
initMap = () => {
const { locations, markers } = this.state;
let map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 59.4827293, lng: -83.1405355 },
zoom: 13
});
// Markers
for (var i = 0; i < locations.length; i++) {
var title = locations[i].name;
var position = new google.maps.LatLng(locations[i].lat, locations[i].lng);
var id = locations[i].id;
var marker = new google.maps.Marker({
map: map,
position: position,
title: title,
animation: google.maps.Animation.DROP,
id: id
});
markers.push(marker);
}
};
render() {
return <div id="map" />;
}
}
function loadJS(src) {
var ref = window.document.getElementsByTagName("script")[0];
var script = window.document.createElement("script");
script.src = src;
script.async = true;
ref.parentNode.insertBefore(script, ref);
}
export default Map;
You store your locations in the state of the App component, but you also have locations in state of the Map component that you use on mount.
You could instead wait with rendering the Map component until the locations request is finished, and then use the locations props in the Map component passed down from App instead.
Example
class App extends Component {
constructor(props) {
super(props);
this.state = {
locations: [],
markers: []
};
}
componentDidMount() {
fetch("correct_foursquare_api_url")
.then(response => response.json())
.then(data => {
const locations = data.response.venues.map(place => ({
id: place.id,
name: place.name,
lat: place.location.lat,
lng: place.location.lng
}));
this.setState({ locations });
});
}
render() {
const { locations, markers } = this.state;
if (locations.length === 0) {
return null;
}
return (
<div className="App">
<Map locations={locations} markers={markers} />
</div>
);
}
}
class Map extends Component {
// ...
initMap = () => {
const { locations, markers } = this.props;
// ...
};
// ...
}

How to access google.maps.Map object with react-google-maps

I have a pretty simple react application using https://github.com/tomchentw/react-google-maps but I'm having difficulty understanding how to get a reference to my current map or how to access the google.maps.Map object in a custom component.
I found this on the repo, but after reading through the posts I'm still a little confused.
I'm starting my application building off of the DirectionsRenderer example.
What I want to do next is add my own custom components for picking the starting point and using the Google Maps autocomplete API.
Yes, I know that the package has a component for that already, but I
need to do a little more than just search for a location on the map.
In order to accomplish my needs I will do something like
const autocomplete = new google.maps.places.Autocomplete(node);
autocomplete.bindTo('bounds', map);
Where node is the element I'm binding the autocomplete functionality and map is an instance of the google.maps.Map object.
My application thus far:
App.jsx
const App = ({ store }) => (
<Provider store={store}>
<div>
<Sidebar>
<StartingPoint defaultText="Choose starting point…" />
</Sidebar>
<GoogleApiWrapper />
</div>
</Provider>
);
GoogleApiWrapper
const GoogleMapHOC = compose(
withProps({
googleMapURL: 'https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=__GAPI_KEY',
loadingElement: <div style={{ height: '100vw' }} />,
containerElement: <div style={{ height: '100vh' }} />,
mapElement: <div style={{ height: '100%' }} />,
}),
withScriptjs,
withGoogleMap,
lifecycle({
componentDidMount() {
const DirectionsService = new google.maps.DirectionsService();
// make google object available to other components
this.props.onLoad(google);
DirectionsService.route({
origin: new google.maps.LatLng(41.8507300, -87.6512600),
destination: new google.maps.LatLng(41.8525800, -87.6514100),
travelMode: google.maps.TravelMode.DRIVING,
}, (result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.setState({
directions: result,
});
} else {
console.error(`error fetching directions ${result}`);
}
});
},
}),
)(props => (
<GoogleMap
ref={props.onMapMounted}
defaultZoom={13}
defaultCenter={new google.maps.LatLng(37.771336, -122.446615)}
>
{props.directions && <DirectionsRenderer directions={props.directions} />}
</GoogleMap>
));
If I'm unable to access the google.maps.Map object outside of the wrapper I would alternatively like to access a reference to the element that contains the map so that I may instantiate a new google.maps.Map(ref_to_elem, options);
Any help would be greatly appreciated!
You can do it by React refs:
<GoogleMap ref={(map) => this._map = map} />
function someFunc () {
//using, for example as:
this._map.getCenter()
this._map.setZoom(your desired zoom);
}
import {GoogleMap, withGoogleMap} from 'react-google-maps';
import {MAP} from 'react-google-maps/lib/constants';
const MapComponent = withGoogleMap(() => (
{/*Here you have access to google.maps.Map object*/}
<GoogleMap ref={(map) => map.context[MAP]}/>
));
const Map = ({locations}) => (
<MapComponentClass
containerElement={MapComponent}
mapElement={MapComponent}
locations={locations}/>
);
export default Map;
Worth pointing out for anyone else googling this that nowdays, using react-google-maps you can simply use the useGoogleMap hook to get access to the Google maps instance
https://react-google-maps-api-docs.netlify.app/#map-instance
import React from 'react'
import { useGoogleMap } from '#react-google-maps/api'
function PanningComponent() {
const map = useGoogleMap()
React.useEffect(() => {
if (map) {
map.panTo(...)
}
}, [map])
return null
}
What I did right now in my react-redux application is I assign global variable map outside of react comnponent GoogleMap:
/*global google*/
// your imports //
var map;
class GoogleMap extends Component {
constructor(props) {
super(props);
this.state = {
// your states
};
}
// your functions
componentWillReceiveProps(nextProps) {
}
componentDidMount() {
// code
// render googlemap
map = new google.maps.Map(this.refs.map, yourMapProps);
// add click event listener to the map
map.addListener('click', function(e) {
//code
});
//viewport listener
map.addListener('idle', function(){
// code
});
}
render() {
return (
<div id="map" ref="map">
{places.map((place) => {
return(<Marker place={place} key={place.key} map={map} />);
})}
</div>
}
}
function mapDispatchToProps(dispatch) {
//code
}
export default connect(mapDispatchToProps)(GoogleMap);
Pass map as props into Child Component:
/*global google*/
import React, { Component } from 'react';
class Marker extends Component {
componentDidMount() {
this.renderMarker();
}
renderMarker() {
var { place, map } = this.props;
place.setMap(map);
}
render() {
return null;
}
}
export default Marker;
I don't know is it good practice. Bu it works. I tried to find the solution how to avoid setting Map Object as global windows.map reading all this stuff about singletons and so on. And then this came to my head. Now if I type window.map in the browser concole I get div id="map"
After thoroughly reading through the react-google-maps documentation, examples, and issues I have come to learn that the package does not support a lot of the things I will need to do for my application.
That being said, I have begun writing my own Google Maps API wrapper based off of the work done by Fullstack React. I've omitted a lot of the utilities used in the below mentioned as they can be found here or here.
That being said my solution is to wrap the google maps container in a higher order component and expose the Map Object via the window object:
App
const App = ({ store }) => (
<Provider store={store}>
<div>
<Sidebar>
<StartingPoint />
{/* TODO */}
</Sidebar>
<GoogleMap />
</div>
</Provider>
);
containers/GoogleMap/wrapper.jsx Google Map Higher Order Component wraps GoogleMap Container
const defaultCreateCache = (options) => {
const opts = options || {};
const apiKey = opts.apiKey;
const libraries = opts.libraries || ['places'];
const version = opts.version || '3.24';
const language = opts.language || 'en';
return ScriptCache({
google: GoogleApi({
apiKey,
language,
libraries,
version,
}),
});
};
const wrapper = options => (WrappedComponent) => {
const createCache = options.createCache || defaultCreateCache;
class Wrapper extends Component {
constructor(props, context) {
super(props, context);
this.scriptCache = createCache(options);
this.scriptCache.google.onLoad(this.onLoad.bind(this));
this.state = {
loaded: false,
google: null,
};
}
onLoad() {
this.GAPI = window.google;
this.setState({ loaded: true, google: this.GAPI });
}
render() {
const props = Object.assign({}, this.props, {
loaded: this.state.loaded,
google: window.google,
});
const mapRef = (el) => { this.map = el; };
return (
<div>
<WrappedComponent {...props} />
<div ref={mapRef} />
</div>
);
}
}
Wrapper.propTypes = {
dispatchGoogleAPI: PropTypes.func,
};
Wrapper.defaultProps = {
dispatchGoogleAPI: null,
};
return Wrapper;
};
export default wrapper;
containers/GoogleMap/index.jsx Google Map Container
class Container extends Component {
constructor(props) {
super(props);
this.loadMap = this.loadMap.bind(this);
this.calcRoute = this.calcRoute.bind(this);
}
componentDidUpdate() {
const { origin, destination, route } = this.props;
this.calcRoute(origin, destination);
}
loadMap(node) {
if (this.props && this.props.google) {
const { google } = this.props;
// instantiate Direction Service
this.directionsService = new google.maps.DirectionsService();
this.directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true,
});
const zoom = 13;
const mapTypeId = google.maps.MapTypeId.ROADMAP;
const lat = 37.776443;
const lng = -122.451978;
const center = new google.maps.LatLng(lat, lng);
const mapConfig = Object.assign({}, {
center,
zoom,
mapTypeId,
});
this.map = new google.maps.Map(node, mapConfig);
this.directionsDisplay.setMap(this.map);
// make the map instance available to other components
window.map = this.map
}
}
calcRoute(origin, destination) {
const { google, route } = this.props;
if (!origin && !destination && !route) return;
const waypts = [];
waypts.push({
location: new google.maps.LatLng(37.415284, -122.076899),
stopover: true,
});
const start = new google.maps.LatLng(origin.lat, origin.lng);
const end = new google.maps.LatLng(destination.lat, destination.lng);
this.createMarker(end);
const request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
};
this.directionsService.route(request, (response, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.directionsDisplay.setDirections(response);
const route = response.routes[0];
console.log(route);
}
});
this.props.calculateRoute(false);
}
createMarker(latlng) {
const { google } = this.props;
const marker = new google.maps.Marker({
position: latlng,
map: this.map,
});
}
render() {
return (
<div>
<GoogleMapView loaded={this.props.loaded} loadMap={this.loadMap} />
</div>
);
}
}
const GoogleMapContainer = wrapper({
apiKey: ('YOUR_API_KEY'),
version: '3', // 3.*
libraries: ['places'],
})(Container);
const mapStateToProps = state => ({
origin: state.Trip.origin,
destination: state.Trip.destination,
route: state.Trip.route,
});
const mapDispatchToProps = dispatch => ({
dispatchGoogleMap: (map) => {
dispatch(googleMap(map));
},
calculateRoute: (route) => {
dispatch(tripCalculation(route));
},
});
const GoogleMap = connect(mapStateToProps, mapDispatchToProps)(GoogleMapContainer);
export default GoogleMap;

how to use ES6 with react native

Working with React-Native and trying to learn ES6 syntax. I had a similar issue yesterday and got the solution. I added
.bind(this)
to my my function calls and the problem was solved. I ran into the same issue again with another function call and I cannot track down what is going on. The error message is the same.
undefined is not a object (evaluating 'this.props.drawer.open')
The function is:
onClickMenu () {
this.props.drawer.open();
}
and it is being called with this:
onPress={this.onClickMenu.bind(this)}
Here is the entire code. If you see something other than this issue that doesn't look right let me know please! *note I have replaced "var" with "let". From what I've read it is proper ES6 syntax to do that everywhere?
'use strict';
const React = require('react-native');
const {
Text,
View,
Component,
StyleSheet,
SwitchAndroid
} = React;
import { Button } from 'react-native-material-design';
import Store from 'react-native-simple-store';
import Underscore from 'underscore';
import RNGMap from 'react-native-gmaps';
import Polyline from 'react-native-gmaps/Polyline';
import Icon from 'react-native-vector-icons/Ionicons';
import SettingsService from './../settings/settings.service';
//import subdivisions from './subdivisions.json';
import commonStyles from './../common/styles';
let accessToken = null;
let userId = null;
let routeId = null;
let subdivisionId = null;
SettingsService.init('Android');
class Map extends Component {
constructor(props) {
super(props)
this.state = {
odometer: 0,
mapWidth: 300,
mapHeight: 300,
enabled: false,
isMoving: false,
currentLocation: undefined,
locationManager: undefined,
paceButtonIcon: 'Start Trip',
navigateButtonIcon: 'navigate',
paceButtonStyle: commonStyles.disabledButton,
// mapbox
center: {
lat: 40.7223,
lng: -73.9878
},
zoom: 10,
markers: []
}
}
componentDidMount() {
Store.get('token').then((token) => {
accessToken = token.access_token;
userId = token.userId;
});
let me = this,
gmap = this.refs.gmap;
this.locationManager = this.props.locationManager;
// location event
this.locationManager.on("location", function(location) {
console.log('- location: ', JSON.stringify(location));
me.setCenter(location);
gmap.addMarker(me._createMarker(location));
me.setState({
odometer: (location.odometer / 1000).toFixed(1)
});
// Add a point to our tracking polyline
if (me.polyline) {
me.polyline.addPoint(location.coords.latitude, location.coords.longitude);
}
});
// http event
this.locationManager.on("http", function(response) {});
// geofence event
this.locationManager.on("geofence", function(geofence) {});
// error event
this.locationManager.on("error", function(error) {
console.log('- ERROR: ', JSON.stringify(error));
});
// motionchange event
this.locationManager.on("motionchange", function(event) {
me.updatePaceButtonStyle();
});
// getGeofences
this.locationManager.getGeofences(function(rs) {
}, function(error) {
console.log("- getGeofences ERROR", error);
});
SettingsService.getValues(function(values) {
values.license = "eddbe81bbd86fa030ea466198e778ac78229454c31100295dae4bfc5c4d0f7e2";
values.orderId = 1;
values.stopTimeout = 0;
//values.url = 'http://192.168.11.120:8080/locations';
me.locationManager.configure(values, function(state) {
me.setState({
enabled: state.enabled
});
if (state.enabled) {
me.initializePolyline();
me.updatePaceButtonStyle()
}
});
});
this.setState({
enabled: false,
isMoving: false
});
}
_createMarker(location) {
return {
title: location.timestamp,
id: location.uuid,
icon: require("image!transparent_circle"),
anchor: [0.5, 0.5],
coordinates: {
lat: location.coords.latitude,
lng: location.coords.longitude
}
};
}
initializePolyline() {
// Create our tracking Polyline
let me = this;
Polyline.create({
width: 12,
points: [],
geodesic: true,
color: '#2677FF'
}, function(polyline) {
me.polyline = polyline;
});
}
onClickMenu () {
this.props.drawer.open();
}
onClickEnable() {
let me = this;
if (!this.state.enabled) {
this.locationManager.start(function() {
me.initializePolyline();
});
} else {
this.locationManager.resetOdometer();
this.locationManager.stop();
this.setState({
markers: [{}],
odometer: 0
});
this.setState({
markers: []
});
if (this.polyline) {
this.polyline.remove(function(result) {
me.polyline = undefined;
});
}
}
this.setState({
enabled: !this.state.enabled
});
this.updatePaceButtonStyle();
}
onClickPace() {
if (!this.state.enabled) {
return;
}
let isMoving = !this.state.isMoving;
this.locationManager.changePace(isMoving);
this.setState({
isMoving: isMoving
});
this.updatePaceButtonStyle();
}
onClickLocate() {
let me = this;
this.locationManager.getCurrentPosition({
timeout: 30
}, function(location) {
me.setCenter(location);
}, function(error) {
console.error('ERROR: getCurrentPosition', error);
me.setState({
navigateButtonIcon: 'navigate'
});
});
}
onRegionChange() {}
setCenter(location) {
this.setState({
navigateButtonIcon: 'navigate',
center: {
lat: location.coords.latitude,
lng: location.coords.longitude
},
zoom: 16
});
}
onLayout() {
let me = this,
gmap = this.refs.gmap;
this.refs.workspace.measure(function(ox, oy, width, height, px, py) {
me.setState({
mapHeight: height,
mapWidth: width
});
});
}
updatePaceButtonStyle() {
let style = commonStyles.disabledButton;
if (this.state.enabled) {
style = (this.state.isMoving) ? commonStyles.redButton : commonStyles.greenButton;
}
this.setState({
paceButtonStyle: style,
paceButtonIcon: (this.state.enabled && this.state.isMoving) ? 'Stop Trip' : 'Start Trip'
});
}
render() {
return (
<View style={commonStyles.container}>
<View style={commonStyles.topToolbar}>
<Icon.Button name="android-options" onPress={this.onClickMenu.bind(this)} backgroundColor="transparent" size={30} color="#000" style={styles.btnMenu} underlayColor={"transparent"} />
<Text style={commonStyles.toolbarTitle}>Background Geolocation</Text>
<SwitchAndroid onValueChange={this.onClickEnable.bind(this)} value={this.state.enabled} />
</View>
<View ref="workspace" style={styles.workspace} onLayout={this.onLayout.bind(this)}>
<RNGMap
ref={'gmap'}
style={{width: this.state.mapWidth, height: this.state.mapHeight}}
markers={this.state.markers}
zoomLevel={this.state.zoom}
onMapChange={(e) => console.log(e)}
onMapError={(e) => console.log('Map error --> ', e)}
center={this.state.center} />
</View>
<View style={commonStyles.bottomToolbar}>
<Icon.Button name={this.state.navigateButtonIcon} onPress={this.onClickLocate.bind(this)} size={25} color="#000" underlayColor="#ccc" backgroundColor="transparent" style={styles.btnNavigate} />
<Text style={{fontWeight: 'bold', fontSize: 18, flex: 1, textAlign: 'center'}}>{this.state.odometer} km</Text>
<Button raised={true}
text={this.state.paceButtonIcon}
onPress={this.onClickPace.bind(this)}
overrides={{backgroundColor:"#e12429",textColor:"#ffffff"}}
style={this.state.paceButtonStyle}></Button>
<Text> </Text>
</View>
</View>
);
}
};
const styles = StyleSheet.create({
workspace: {
flex: 1
}
});
module.exports = Map;
UPDATE:
debugging via adb in the terminal shows the same error
So here is rest of code. to troubleshoot. I added the project files to a plunker. it is a demo project that i am working with. plunker
'use strict';
const React = require('react-native');
const {
Text,
Component,
StyleSheet,
AppRegistry
} = React;
import Map from './map/map';
import Drawer from 'react-native-drawer';
import Settings from './settings/settings.android';
import Icon from 'react-native-vector-icons/Ionicons';
import BackgroundGeolocation from 'react-native-background-geolocation-android';
global.bgGeo = BackgroundGeolocation;
class App extends Component {
onClickMenu() {
this.props.refs.drawer.open();
}
render() {
return (
<Drawer ref="drawer" side="right" acceptPan={false} content={<Settings drawer={this.refs.drawer} locationManager={BackgroundGeolocation} />}>
<Map drawer={this.refs.drawer} locationManager={BackgroundGeolocation} />
</Drawer>
);
}
};
module.exports = App;
UPDATE:
I dont think you can pass through refs to components in such a way,
certainly it would not work in React and I dont think it would work
in such a way in React-Native either.
I'm not clear why you are trying to .open the Drawer from the
Map component as it looks like the Map component can only be
accessed when the Drawer is open, but, if you want to access parent
behaviours from children a good pattern is to pass through functions
for children to execute (you could argue that this is actually bad
and that passing events around is a more robust pattern).
I've never used the library so I'm not totally clear on its usage but
you can pass functions through like this:
class Application extends Component {
closeControlPanel = () => {
this.refs.drawer.close()
};
openControlPanel = () => {
this.refs.drawer.open()
};
render () {
return (
<Drawer
ref="drawer"
content={<ControlPanel />}
>
<Map onMenuClose={ this.closeControlPanel.bind( this ) } />
</Drawer>
)
}
})
In this case this.props.onMenuClose should be attached to an action, which, when executed will trigger the function from the parent and execute the this.refs.drawer.close function.

Categories

Resources