Reputation: 2094
I seemingly succesfully implemented google maps into my react app (get's user location and allows to move marker), but I'm getting random error 'TypeError: Cannot read property 'maps' of undefined'. Sometimes everything works perfectly, other time when I refresh i get this error. I'm not sure which chunk of code I should provide so maybe I'll post my full map component and index.js file
map:
import React from 'react';
class GoogleMap extends React.Component {
constructor(props) {
super(props);
//const getCoords = this.props.getCoords;
this.handleLocationError = this.handleLocationError.bind(this);
this.state = {
lat: '',
lon: ''
}
}
getCoords() {
const lat = this.state.lat;
const lon = this.state.lon;
this.props.getCoords(lat, lon)
}
componentDidMount() {
var map, infoWindow;
map = new window.google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 15
});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var marker = new window.google.maps.Marker({
position: {
lat: position.coords.latitude,
lng: position.coords.longitude
},
map: map,
draggable: true,
title: 'Hello World!'
})
this.setState({
lat: position.coords.latitude,
lon: position.coords.longitude
})
this.getCoords();
document.getElementById('test').innerHTML = '<p>Want to export: Current Lat: ' + position.coords.latitude + ' Current Lng: ' + position.coords.longitude + '</p>';
map.setCenter(pos);
//marker listeners
window.google.maps.event.addListener(marker, 'dragstart', function () {
console.log('marker dotkniety');
document.getElementById('test').innerHTML = '<p>Currently dragging marker...</p>';
});
window.google.maps.event.addListener(marker, 'dragend', (e) => {
console.log('marker upuszczony');
document.getElementById('test').innerHTML = '<p>Want to export: Current Lat: ' + e.latLng.lat().toFixed(3) + ' Current Lng: ' + e.latLng.lng().toFixed(3) + '</p>';
console.log(this, 'this inside the event listener');
this.setState(({
lat: e.latLng.lat(),
lon: e.latLng.lng()
}))
this.getCoords();
});
}, () => {
this.handleLocationError(true, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
this.handleLocationError(false, map.getCenter());
}
console.log('DID MOUNT');
console.log(this);
console.log(this.state);
}
handleLocationError(browserHasGeolocation, pos, map) {}
render() {
return (
<div>
<div id='map' />
<div id='test' />
</div>
)
}
}
export default GoogleMap
and index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBHek4tQK4jSQhVSoxw4s4c8tz_1z3xuNI&callback=initMap">
</script>
<title>App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
</body>
</html>
Ill be grateful for solutions / tips or reasons why it acts this way.
Upvotes: 1
Views: 357
Reputation: 473
install google maps as npm package
$ npm install google-maps
and then import it on your component GoogleMapComponent.jsx:
import React from 'react';
import GoogleMapsLoader from 'google-maps';
GoogleMapsLoader.KEY = 'qwertyuiopasdfghjklzxcvbnm';
class GoogleMap extends React.Component {
constructor(props) {
super(props);
//const getCoords = this.props.getCoords;
this.handleLocationError = this.handleLocationError.bind(this);
this.state = {
lat: '',
lon: ''
}
}
componentDidMount() {
GoogleMapsLoader.load((google) => {
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 15
});
// rest of the code with maps
});
// rest of the code with react
}
Upvotes: 2