can not move location and create marker mapbox react - javascript

this code is o create a marker using the value introduced by the user, and make this marker fixed.
but I don't even can create the marker, nothing happen.
it's stick in the initial location after rendering. I taught maybe it was a lat and lng order but I try that and it's keep loading.
I try also to remove flyTo but nothing changed
export default function Map() {
const mapContainer = useRef(null);
const [lng, setLng] = useState(-70.9);
const [lat, setLat] = useState(42.35);
const [zoom, setZoom] = useState(9);
const [searchValue, setSearchValue] = useState("");
useEffect(() => {
const map = new mapboxgl.Map({
container: mapContainer.current,
style: "mapbox://styles/mapbox/streets-v11",
center: [lng, lat],
zoom: zoom,
});
map.addControl(new mapboxgl.NavigationControl(), "top-right");
map.on("move", () => {
setLng(map.getCenter().lng.toFixed(4));
setLat(map.getCenter().lat.toFixed(4));
setZoom(map.getZoom().toFixed(2));
});
}, []); // eslint-disable-line react-hooks/exhaustive-deps
function getCoordinates(placesContent) {
const { center, place_name } = placesContent.features[0];
return {
coordinates: center.reverse(),
name: place_name,
};
}
const changeMapCenter = async () => {
const map = new mapboxgl.Map({
container: mapContainer.current,
style: "mapbox://styles/mapbox/streets-v11",
center: [lng, lat],
zoom: zoom,
});
return fetch(
`${MAPBOX_PLACES_API}${searchValue}${REST_PLACES_URL}`,
FETCH_HEADERS
)
.then((res) => res.json())
.then((apiData) => {
console.log("apidata=>", apiData);
const { coordinates } = getCoordinates(apiData);
console.log("coordinates=>", coordinates);
map.flyTo(coordinates);
new mapboxgl.Marker().setLngLat(coordinates).addTo(map);
});
};
const handleChange = (event) => {
setSearchValue(event.target.value);
};
return (
<div className="mapBox">
<div className="sidebar">
Longitude: {lng} | Latitude: {lat} | Zoom: {zoom}
<div>
<label>create your spot collection</label>
<input
type="text"
id="spotLocation"
onChange={handleChange}
value={searchValue}
/>
<button onClick={changeMapCenter}>search and create </button>
</div>
</div>
<div className="map-container" ref={mapContainer} />
</div>
);
}

Try saving the map in a state and use setCenter
const [ customMap, setMap ] = useState({ lat: 0, lng: 0}) // set your own initial value
useEffect(() => {
const map = new mapboxgl.Map({
container: mapContainer.current,
style: "mapbox://styles/mapbox/streets-v11",
center: [lng, lat],
zoom: zoom,
});
map.addControl(new mapboxgl.NavigationControl(), "top-right");
map.on("move", () => {
setLng(map.getCenter().lng.toFixed(4));
setLat(map.getCenter().lat.toFixed(4));
setZoom(map.getZoom().toFixed(2));
});
setMap(map);
}, []);
const handleChange = (event) => {
// i assume event.target.value contains the coordinates
// example 929292, 2929292
setSearchValue(event.target.value)
};
const onSubmit = () => {
let coordinates = searchValue.split(',')
customMap.setCenter({ lat: coordinates[0], lng: coordinates[1]});
}

Related

Updating Markers to Google Maps in google-map-react

onGoogleApiLoaded not invoked on locations data change, Is there any way to achieve this?
I tried to use useEffect to load markers but then I have to save map and maps objects in useRef as well as markers
Is there any easier way to achieve this?
import { useEffect, useRef } from 'react';
import GoogleMapReact from 'google-map-react';
export type SimpleMapProps = {
locations: any[];
};
export default function SimpleMap({ locations }: SimpleMapProps) {
const defaultProps =
locations.length > 0
? {
center: {
lat: locations[0].Lat,
lng: locations[0].Lon
},
zoom: 11
}
: {
center: {
lat: 0,
lng: 0
},
zoom: 11
};
const handleApiLoadData = (map: any, maps: any) => {
for (let i = 0; i < locations.length; i++) {
const { Lat, Lon, hn, cur, rate } = locations[i];
const marker = new maps.Marker({
animation: maps.Animation.DROP,
position: { lat: Lat, lng: Lon },
map
});
marker.customInfowindow = new maps.InfoWindow({
content: `<div>${hn} </br> (${cur} ${rate})</div>`
});
marker.addListener('click', () => {
marker.customInfowindow.open(map, marker);
});
}
};
return (
// Important! Always set the container height explicitly
<div style={{ height: '50vh', width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{
key: 'XXXXXXXXXXXXXXX'
}}
center={defaultProps.center}
zoom={defaultProps.zoom}
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={({ map, maps }) => handleApiLoadData(map, maps)}
/>
</div>
);
}

Passing Data Using Props to Display Polylines with Google Maps

Here is the reactjs code for displaying the movement of a vehicle on google map.
In the code, for the path array, latitude and longitude coordinates are assigned as hard-code values.
What I need is, how should pass latitude and longitude coordinates to "path" array from another component using props.
import React from "react";
import {
withGoogleMap,
withScriptjs,
GoogleMap,
Polyline,
Marker,
} from "react-google-maps";
class Map extends React.Component {
state = {
progress: [],
};
path = [
{ lat: 18.558908, lng: -68.389916 },
{ lat: 18.558853, lng: -68.389922 },
{ lat: 18.558375, lng: -68.389729 },
{ lat: 18.558032, lng: -68.389182 },
{ lat: 18.55805, lng: -68.388613 },
{ lat: 18.558256, lng: -68.388213 },
{ lat: 18.558744, lng: -68.387929 },
];
velocity = 5;
initialDate = new Date();
getDistance = () => {
// seconds between when the component loaded and now
const differentInTime = (new Date() - this.initialDate) / 1000; // pass to seconds
return differentInTime * this.velocity; // d = v*t -- thanks Newton!
};
componentDidMount = () => {
this.interval = window.setInterval(this.moveObject, 1000);
};
componentWillUnmount = () => {
window.clearInterval(this.interval);
};
moveObject = () => {
const distance = this.getDistance();
if (!distance) {
return;
}
let progress = this.path.filter(
(coordinates) => coordinates.distance < distance
);
const nextLine = this.path.find(
(coordinates) => coordinates.distance > distance
);
if (!nextLine) {
this.setState({ progress });
return; // it's the end!
}
const lastLine = progress[progress.length - 1];
const lastLineLatLng = new window.google.maps.LatLng(
lastLine.lat,
lastLine.lng
);
const nextLineLatLng = new window.google.maps.LatLng(
nextLine.lat,
nextLine.lng
);
// distance of this line
const totalDistance = nextLine.distance - lastLine.distance;
const percentage = (distance - lastLine.distance) / totalDistance;
const position = window.google.maps.geometry.spherical.interpolate(
lastLineLatLng,
nextLineLatLng,
percentage
);
progress = progress.concat(position);
this.setState({ progress });
};
componentWillMount = () => {
this.path = this.path.map((coordinates, i, array) => {
if (i === 0) {
return { ...coordinates, distance: 0 }; // it begins here!
}
const { lat: lat1, lng: lng1 } = coordinates;
const latLong1 = new window.google.maps.LatLng(lat1, lng1);
const { lat: lat2, lng: lng2 } = array[0];
const latLong2 = new window.google.maps.LatLng(lat2, lng2);
// in meters:
const distance = window.google.maps.geometry.spherical.computeDistanceBetween(
latLong1,
latLong2
);
return { ...coordinates, distance };
});
console.log(this.path);
};
render = () => {
return (
<GoogleMap
defaultZoom={16}
defaultCenter={{ lat: 18.559008, lng: -68.388881 }}
>
{this.state.progress && (
<>
<Polyline
path={this.state.progress}
options={{ strokeColor: "#FF0000 " }}
/>
<Marker
position={this.state.progress[this.state.progress.length - 1]}
/>
</>
)}
</GoogleMap>
);
};
}
const MapComponent = withScriptjs(withGoogleMap(Map));
export default () => (
<MapComponent
googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places"
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `400px`, width: "940px" }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
);
Here is sample data from json object, which I get from other component.I need to pass this data using props to the above path array.
[]
0: {lat: 6.8667528, lng: 79.8769134}
1: {lat: 6.8667112, lng: 79.8769667}
2: {lat: 6.8666556, lng: 79.8769856}
3: {lat: 6.8666023, lng: 79.8769823}
4: {lat: 6.8665584, lng: 79.8770412}
5: {lat: 6.8665478, lng: 79.8771573}
6: {lat: 6.8665295, lng: 79.8772695}
7: {lat: 6.8664823, lng: 79.8774434}
8: {lat: 6.8664434, lng: 79.8777684}
9: {lat: 6.8664023, lng: 79.87823}
10: {lat: 6.8663373, lng: 79.8786712}
11: {lat: 6.86628, lng: 79.87902}
12: {lat: 6.8662312, lng: 79.879335}
13: {lat: 6.8662145, lng: 79.8795562}
14: {lat: 6.8662095, lng: 79.879695}
15: {lat: 6.8661978, lng: 79.8797523}
16: {lat: 6.8659873, lng: 79.8798639}
Can anyone help me to build this? Thanks for your help!
This is a sample code Note: use your own API key for the code to work) and a code snippet below on how I implement it. In the index.js, I put the path array in json file then imported the json file to be used as an element in my map. Then in my Map.js, I set the constuctor(props) and super(props). I put the react-google-maps <GoogleMap> in the render inside the GoogleMapExample variable. Then I use this variable in the return. In the componentWillMount function of your code, you need to use this.props.path.map to get the value of your path from the props.
Index.js
import React, { Component } from "react";
import { render } from "react-dom";
import { withScriptjs } from "react-google-maps";
import Map from "./Map";
import "./style.css";
import jsonPath from "./data.json";
const App = () => {
const MapLoader = withScriptjs(Map);
return (
<MapLoader
path={jsonPath}
googleMapURL="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry,places"
loadingElement={<div style={{ height: `100%` }} />}
/>
);
};
render(<App />, document.getElementById("root"));
Map.js
import React, { Component } from "react";
import {
withGoogleMap,
GoogleMap,
Polyline,
Marker
} from "react-google-maps";
class Map extends Component {
constructor(props) {
super(props);
this.state = {
progress: []
};
}
velocity = 5;
initialDate = new Date();
getDistance = () => {
// seconds between when the component loaded and now
const differentInTime = (new Date() - this.initialDate) / 1000; // pass to seconds
return differentInTime * this.velocity; // d = v*t -- thanks Newton!
};
componentDidMount = () => {
this.interval = window.setInterval(this.moveObject, 1000);
console.log(this.props.path);
};
componentWillUnmount = () => {
window.clearInterval(this.interval);
};
moveObject = () => {
const distance = this.getDistance();
if (!distance) {
return;
}
let progress = this.path.filter(
coordinates => coordinates.distance < distance
);
const nextLine = this.path.find(
coordinates => coordinates.distance > distance
);
if (!nextLine) {
this.setState({ progress });
return; // it's the end!
}
const lastLine = progress[progress.length - 1];
const lastLineLatLng = new window.google.maps.LatLng(
lastLine.lat,
lastLine.lng
);
const nextLineLatLng = new window.google.maps.LatLng(
nextLine.lat,
nextLine.lng
);
// distance of this line
const totalDistance = nextLine.distance - lastLine.distance;
const percentage = (distance - lastLine.distance) / totalDistance;
const position = window.google.maps.geometry.spherical.interpolate(
lastLineLatLng,
nextLineLatLng,
percentage
);
progress = progress.concat(position);
this.setState({ progress });
};
componentWillMount = () => {
this.path = this.props.path.map((coordinates, i, array) => {
if (i === 0) {
return { ...coordinates, distance: 0 }; // it begins here!
}
const { lat: lat1, lng: lng1 } = coordinates;
const latLong1 = new window.google.maps.LatLng(lat1, lng1);
const { lat: lat2, lng: lng2 } = array[0];
const latLong2 = new window.google.maps.LatLng(lat2, lng2);
// in meters:
const distance = window.google.maps.geometry.spherical.computeDistanceBetween(
latLong1,
latLong2
);
return { ...coordinates, distance };
});
console.log(this.path);
};
render() {
const GoogleMapExample = withGoogleMap(props => (
<GoogleMap
defaultZoom={16}
defaultCenter={{ lat: 6.8667528, lng: 79.8769134 }}
>
{this.state.progress && (
<>
<Polyline
path={this.state.progress}
options={{ strokeColor: "#FF0000 " }}
/>
<Marker
position={this.state.progress[this.state.progress.length - 1]}
/>
</>
)}
</GoogleMap>
));
return (
<div>
<GoogleMapExample
containerElement={<div style={{ height: `500px`, width: "500px" }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
}
export default Map;

Gatsby JS Uncaught TypeError React Google Maps API

I used React Google Maps api in one of my Gatsby sites. I created the following component and imported it into one of my pages. Here is the code for the compenent.
import React, { useState } from "react"
import {
GoogleMap,
useLoadScript,
Marker,
InfoWindow,
} from "#react-google-maps/api"
import { useStaticQuery, graphql } from "gatsby"
import mapStyles from "./mapStyles"
const Indianapolis = {
lat: 39.768402,
lng: -86.158066,
}
const mapContainerStyle = {
height: "100%",
width: "100%",
}
const options = {
styles: mapStyles,
disableDefaultUI: true,
zoomControl: true,
}
const Map = () => {
const data = useStaticQuery(graphql`
{
allKmlPoint {
edges {
node {
properties {
name
Longitude
Latitude
FRP_Project_Numbers
description
styleUrl
styleHash
}
id
}
}
}
}
`)
const [selected, setSelected] = useState(null)
const frpLocation = data.allKmlPoint.edges
//console.log(process.env.GATSBY_GOOGLE_MAPS_API_KEY)
const { isLoaded, loadError } = useLoadScript({
googleMapsApiKey: process.env.GATSBY_GOOGLE_MAPS_API_KEY,
})
const mapRef = React.useRef()
const onMapLoad = React.useCallback(map => {
mapRef.current = map
console.log(map)
}, [])
const onUnmount = React.useCallback(function callback(map) {
console.log(map)
}, [])
if (loadError) return "Error"
if (!isLoaded) {
return "Loading..."
}
//console.log("comes here")
return (
<div className="map-container">
<span className="top-text">Project</span>
<span className="horizontal-line"></span>
<span className="bottom-text">
Locati<span className="full-color">o</span>ns
</span>
<span className="map-blurb">
FRP has a project portfolio across a wide geographic region. Click the
Map to Zoom and pan to the project locations for various market types.
</span>
<div className="map-wrapper">
<GoogleMap
zoom={8}
center={Indianapolis}
mapContainerStyle={mapContainerStyle}
options={options}
onUnmount={onUnmount}
onLoad={onMapLoad}
>
{frpLocation.map(marker => (
<Marker
key={marker.node.id}
position={{
lat: parseFloat(marker.node.properties.Latitude),
lng: parseFloat(marker.node.properties.Longitude),
}}
icon={{
url: `icon_${marker.node.properties.styleUrl.slice(-6)}.svg`,
origin: new window.google.maps.Point(0, 0),
anchor: new window.google.maps.Point(15, 15),
scaledSize: new window.google.maps.Size(30, 30),
}}
onClick={() => {
setSelected(marker)
}}
/>
))}
{selected ? (
<InfoWindow
position={{
lat: parseFloat(selected.node.properties.Latitude),
lng: parseFloat(selected.node.properties.Longitude),
}}
onCloseClick={() => {
setSelected(null)
}}
>
<div>
<p>{selected.node.properties.name}</p>
</div>
</InfoWindow>
) : null}
</GoogleMap>
</div>
</div>
)
}
export default Map
The page works just fine. However, when I try to move away from the page (which has the google map) to another page (in Gatsby), the page transition is not smooth. Gatsby reloads the new page entirely. The console gives me the following error:
Uncaught TypeError: a is undefined
ZU marker.js:48
<anonymous> marker.js:45
setTimeout handler*_.bn common.js:17
<anonymous> marker.js:45
H js:207
trigger js:204
remove js:207
removeListener js:203
unregisterEvent reactgooglemapsapi.esm.js:142
unregisterEvents reactgooglemapsapi.esm.js:150
componentWillUnmount reactgooglemapsapi.esm.js:2118
wrappedMethod react-hot-loader.development.js:707
React 27
unlisten index.js:103
unlisten index.js:101
promise callback*componentDidMount/refs.unlisten< index.js:99
navigate history.js:100
navigate history.js:99
navigate navigation.js:120
promise callback*navigate navigation.js:84
___navigate navigation.js:162
onClick index.js:256
onClick index.js:477
React 22
marker.js:48:38
There are several instances of this error on the console (I think as many as the number of markers I have on my map).
I am sure it is a simple fix to get rid of this error. Can someone help
UPDATE:Based on what #Ferran said, I used the following code, Still does not work:
I created a useState hook as you said.
const [frpMap, setFrpMap] = useState(null)
mapRef.current = map
...
const onLoad = React.useCallback(function callback(map) {
setFrpMap(map)
}, [])
const onUnmount = React.useCallback(function callback(map) {
setFrpMap(null)
mapRef.current = null
//console.log(map)
}, [])
I think I am not sure how to use the map variable set in the setFrpMap hook to render the GoogleMap.
So, when I do setFrpMap(null) on unmount nothing really happens.
You aren't unmounting your map so it breaks when the routing changes. This is not doing anything:
const onUnmount = React.useCallback(function callback(map) {
console.log(map)
}, [])
I would suggest an approach using useState hook, in order to mount and unmount/dispose the map when needed:
import React, { useState } from "react"
import {
GoogleMap,
useLoadScript,
Marker,
InfoWindow,
} from "#react-google-maps/api"
import { useStaticQuery, graphql } from "gatsby"
import mapStyles from "./mapStyles"
const Indianapolis = {
lat: 39.768402,
lng: -86.158066,
}
const mapContainerStyle = {
height: "100%",
width: "100%",
}
const options = {
styles: mapStyles,
disableDefaultUI: true,
zoomControl: true,
}
const Map = () => {
const [map, setMap] = React.useState(null)
const data = useStaticQuery(graphql`
{
allKmlPoint {
edges {
node {
properties {
name
Longitude
Latitude
FRP_Project_Numbers
description
styleUrl
styleHash
}
id
}
}
}
}
`)
const [selected, setSelected] = useState(null)
const frpLocation = data.allKmlPoint.edges
//console.log(process.env.GATSBY_GOOGLE_MAPS_API_KEY)
const { isLoaded, loadError } = useLoadScript({
googleMapsApiKey: process.env.GATSBY_GOOGLE_MAPS_API_KEY,
})
const mapRef = React.useRef()
const onMapLoad = React.useCallback(map => {
mapRef.current = map
setMap(map)
console.log(map)
}, [])
const onUnmount = React.useCallback(function callback(map) {
console.log(map)
setMap(null)
}, [])
if (loadError) return "Error"
if (!isLoaded) {
return "Loading..."
}
//console.log("comes here")
return (
<div className="map-container">
<span className="top-text">Project</span>
<span className="horizontal-line"></span>
<span className="bottom-text">
Locati<span className="full-color">o</span>ns
</span>
<span className="map-blurb">
FRP has a project portfolio across a wide geographic region. Click the
Map to Zoom and pan to the project locations for various market types.
</span>
<div className="map-wrapper">
<GoogleMap
zoom={8}
center={Indianapolis}
mapContainerStyle={mapContainerStyle}
options={options}
onUnmount={onUnmount}
onLoad={onMapLoad}
>
{frpLocation.map(marker => (
<Marker
key={marker.node.id}
position={{
lat: parseFloat(marker.node.properties.Latitude),
lng: parseFloat(marker.node.properties.Longitude),
}}
icon={{
url: `icon_${marker.node.properties.styleUrl.slice(-6)}.svg`,
origin: new window.google.maps.Point(0, 0),
anchor: new window.google.maps.Point(15, 15),
scaledSize: new window.google.maps.Size(30, 30),
}}
onClick={() => {
setSelected(marker)
}}
/>
))}
{selected ? (
<InfoWindow
position={{
lat: parseFloat(selected.node.properties.Latitude),
lng: parseFloat(selected.node.properties.Longitude),
}}
onCloseClick={() => {
setSelected(null)
}}
>
<div>
<p>{selected.node.properties.name}</p>
</div>
</InfoWindow>
) : null}
</GoogleMap>
</div>
</div>
)
}
export default Map
The idea is to initially set as null your map and set it in your onLoad function with:
const onMapLoad = React.useCallback(map => {
mapRef.current = map
setMap(map)
console.log(map)
}, [])
Note: adapt the snippet to your needs.
Since the callback is receiving the map as a parameter, you are able to use it along with useState hook.
On the other hand, use the opposite way when unmounting the map (onUnmount):
const onUnmount = React.useCallback(function callback(map) {
console.log(map)
setMap(null) // alternatively use map.data=null
}, [])
The same approach, your callback is receiving the map though you don't need it so, you can set the map object as null.
You can check the docs for further details.
const onUnmount = React.useCallback(function callback(map) {
map.data = null
}, [])
did the trick

Why can I not delete Google Markers?

I have methods of rendering Markers as shown below. I'm passing markers array from props and rendering it each time componentDidUpdate triggered. The problem is my old markers is not removing from maps. For example if I had 1 coordinates inside my parent component and update it with new ones, the new one appears and the old one stands still.
`
import React from 'react';
const google = window.google;
export class GMap extends React.Component {
mapRef = React.createRef();
directionsService
directionsRenderer
map;
componentDidMount() {
this.initMap();
const { onClick } = this.props;
onClick && this.onMapClick();
}
componentDidUpdate() {
const { markers } = this.props;
this.calcRoute();
if (markers && markers.length > 0) {
this.clear(markers);
this.renderMarkers(markers);
}
}
initMap() {
this.directionsService = new google.maps.DirectionsService();
this.directionsRenderer = new google.maps.DirectionsRenderer();
const mapOptions = {
zoom: 13,
center: { lat: 40.386119, lng: 49.860925 }
}
const map = new google.maps.Map(document.getElementById('map'), mapOptions);
this.map = map;
this.directionsRenderer.setMap(map);
}
onMapClick() {
this.map.addListener('click', (e) => {
this.props.onClick(e);
})
}
renderMarkers(markers) {
markers.forEach(position => {
const marker = new google.maps.Marker({ position });
marker.setMap(this.map);
})
}
calcRoute() {
const { directions } = this.props;
if (directions) {
const [{ lat: fLat, lng: fLng }, { lat: tLat, lng: tLng }] = directions;
if (fLat && fLng && tLat && tLng) {
var request = {
origin: { lat: fLat, lng: fLng },
destination: { lat: tLat, lng: tLng },
travelMode: 'DRIVING'
};
this.directionsService.route(request, (result, status) => {
if (status === 'OK') {
this.directionsRenderer.setDirections(result);
}
});
}
}
}
render() {
return (
<div id='map' ref={this.mapRef} />
)
}
}
`
How are you removing the markers? All I can see in the posted code is this.clear(markers) with no reference to clear. Try doing something like this:
clear(markers) {
for(let i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
Hope this helps!

google-maps-react user location not working

I am trying to display the user location on the map using google-maps-react. I followed the fullstack tutorial, but I just can't seem to display the user location. I will display my Map.js Component below. Please help me point out what I am doing wrong. Thank you.
import React, { Component } from 'react'
import ReactDOM from 'react-dom';
class Map extends Component {
constructor(props) {
super(props);
const {lat, lng} = this.props.initialCenter;
this.state = {
currentLocation: {
lat: lat,
lng: lng
}
}
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.google !== this.props.google) {
this.loadMap();
}
if (prevState.currentLocation !== this.state.currentLocation) {
this.recenterMap();
}
}
recenterMap() {
const map = this.map;
const curr = this.state.currentLocation;
const google = this.props.google;
const maps = google.maps;
if (map) {
let center = new maps.LatLng(curr.lat, curr.lng)
map.panTo(center)
}
}
componentDidMount() {
if (this.props.centerAroundCurrentLocation) {
if (navigator && navigator.geolocation) {
navigator.geolocation.getCurrentPosition((pos) => {
const coords = pos.coords;
this.setState({
currentLocation: {
lat: coords.latitude,
lng: coords.longitude
}
})
})
}
}
this.loadMap();
}
loadMap() {
if (this.props && this.props.google) {
// google is available
const {google} = this.props;
const maps = google.maps;
const mapRef = this.refs.map;
const node = ReactDOM.findDOMNode(mapRef);
let {initialCenter, zoom} = this.props;
const {lat, lng} = initialCenter;
const center = new maps.LatLng(lat, lng);
const mapConfig = Object.assign({}, {
center: center,
zoom: zoom
})
this.map = new maps.Map(node, mapConfig);
}
}
render() {
const style = {
width: '100vw',
height: '100vh'
}
return (
<div ref='map' style={style}>
Loading map...
</div>
)
}
}
Map.propTypes = {
google: React.PropTypes.object,
zoom: React.PropTypes.number,
initialCenter: React.PropTypes.object,
centerAroundCurrentLocation: React.PropTypes.bool
}
Map.defaultProps = {
zoom: 13,
// San Francisco, by default
initialCenter: {
lat: 37.774929,
lng: -122.419416
},
centerAroundCurrentLocation: false
}
export default Map

Categories

Resources