Geocode in react app not updating the map React - reactjs

I'm trying to get the map geocode but when the map is loading it never uses the new lat and lng. It's always the original one from the useState.
const CustomMap = () => {
const [customLat, setCustomLat] = useState(0);
const [customLng, setCustomLng] = useState(0);
useEffect(() => {
Geocode.fromAddress("Eiffel Tower").then(
(response) => {
const { lat, lng } = response.results[0].geometry.location;
setCustomLat(lat);
setCustomLng(lng);
},
(error) => {
console.log(error.data);
}
);
}, [])
return (
<GoogleMapReact
bootstrapURLKeys={{ key: 'API_KEY' }}
defaultCenter={{ lat: customLat, lng: customLng }}
defaultZoom={11}>
</GoogleMapReact>
)
}
Even though in the console I can see it's getting the map with url of the Eifell towel.
Fetch finished loading: GET "https://maps.googleapis.com/maps/api/geocode/json?address=Eiffel%20Tower&key=KEY&language=en".
That is the last console log but the center of the map is still the original ones.

You are using the default, this only works on the first render, to update you need use the center, like this
<GoogleMapReact
bootstrapURLKeys={{ key: 'API_KEY' }}
defaultCenter={{ lat: customLat, lng: customLng }}
center = {{lat: customLat, lng: customLng}}
defaultZoom={11}>
</GoogleMapReact>

Related

How to add Google Maps Waypoints in react.js?

I am trying to implement Google Maps Directions Waypoints using #react-google-maps/api library to show the directions between starting and ending points.
With mock data coordinates it seems to work, but not with the data coming from the api/json file.
Here is the Codesandbox link
And the code below
import React, { useState } from "react";
import {
DirectionsRenderer,
DirectionsService,
GoogleMap,
LoadScript,
Marker
} from "#react-google-maps/api";
const containerStyle = {
width: "100%",
height: "900px"
};
const center = {
lat: 51.4332,
lng: 7.6616
};
const options = {
disableDefaultUI: true,
zoomControl: true,
fullscreenControl: true,
maxZoom: 17
};
export default function App({ parks }) {
const [directions, setDirections] = useState();
const directionsCallback = React.useCallback((response) => {
console.log(response);
if (response !== null) {
if (response.status === "OK") {
console.log("response", response);
setDirections(response);
} else {
console.log("response: ", response);
}
}
}, []);
//destination
const destinationPark = parks.features.find(
(park) => park.properties.id === 28007
);
//origin
const originPark = parks.features.find(
(park) => park.properties.id === 35299
);
const google = window.google;
// data to add as waypoints
const waypointsParks = parks.features.filter(
(park) => park.properties.id !== 28007 && park.properties.id !== 35299
);
return (
<div style={{ width: "100%", height: "100%" }}>
<LoadScript googleMapsApiKey={google_api_key}>
<GoogleMap
mapContainerStyle={containerStyle}
center={center}
zoom={6}
options={options}
>
<Marker
position={{
lat: parseFloat("52.50920109083271"),
lng: parseFloat("13.416411897460808")
}}
/>
)
<DirectionsService
callback={directionsCallback}
options={{
destination: `${destinationPark.properties.coordinates[1]}, ${destinationPark.properties.coordinates[0]}`,
origin: `${originPark.properties.coordinates[1]}, ${originPark.properties.coordinates[0]}`,
travelMode: "DRIVING"
// waypoints: [
// {
// location: new google.maps.LatLng(
// 52.596714626379296,
// 14.70278827986568
// )
// },
// {
// location: new google.maps.LatLng(
// 52.56193313494678,
// 11.52648542963747
// )
// }
// ]
}}
/>
<DirectionsRenderer
options={{
directions: directions
}}
/>
</GoogleMap>
</LoadScript>
</div>
);
}
Any help will be appreciated.
Assuming the failure is the following based upon codesandbox log.
Directions request returned no results.
Your application must handle the case where no results are found.
If you feel like this is a mistake, please provide a simplified example with just the origin, destination, waypoints, etc that you believe should return a result.

can't drag to move, zoom in or out google-maps-react

I'm trying to display a couple of markers in a map. On button click, I add in a marker and recenter the map to show all the markers.
function MapContainer(props) {
var bounds = new props.google.maps.LatLngBounds();
const [markers, setMarkers] = useState([
{
lat: 55.378,
lng: 3.436
},
{
lat: 37.0902,
lng: 95.712
}
]);
const adjustMap = (mapProps, map) => {
map.fitBounds(bounds);
}
useEffect(() => {
for (var i = 0; i < markers.length; i++)
bounds.extend(new props.google.maps.LatLng(markers[i].lat, markers[i].lng))
}, [markers])
return (
<>
<div className={props.className}>
<Map
google={props.google}
style={{ borderRadius: '10px'}}
zoom={7}
bounds={bounds}
onBoundsChanged={adjustMap}
>
{
markers.map((item) => {
return (
<Marker position={{lat: item.lat, lng: item.lng}}/>
)
})
}
</Map>
</div>
<button onClick={(e) => { e.preventDefault(); console.log("hehe"); const hoho = [...markers, {lat: 59.913, lng: 10.752}]; setMarkers(hoho)}}>Add marker</button>
</>
);
}
Now the issue is, I can't drag to move the map, nor can I zoom in or out. If I remove the onBoundsChanged property, I can drag and zoom, but if I include it, dragging and zooming doesn't work.
How can I fix this?
You are in an infinite loop since because react is not doing a deep diff on your props and your props are continuously changing because it is a new LatLngBounds object over and over and over. Try passing primitives as props instead of an object.
See https://github.com/googlemaps/js-samples/issues/946 for further discussion around this.

Centralize google map issue

import React, {
useState
} from "react";
import GoogleMapReact from "google-map-react";
function GMap() {
const [latLgn, setLatLgn] = useState([{
lng: 24.7536,
lat: 59.437
},
{
lng: 24.7303,
lat: 59.4393
},
{
lng: 24.7387,
lat: 59.4497
},
]);
const [tallinn] = useState({
center: { // where i want to be centerd
lng: 24.7536,
lat: 59.437,
},
zoom: 10,
});
// Fit map to its bounds after the api is loaded
const apiIsLoaded = (map, maps, latlgn) => {
// Get bounds by our latlgn
const bounds = getMapBounds(map, maps, latlgn);
// Fit map to bounds
map.fitBounds(bounds);
// Bind the resize listener
bindResizeListener(map, maps, bounds);
};
// Re-center map when resizing the window
const bindResizeListener = (map, maps, bounds) => {
maps.event.addDomListenerOnce(map, "idle", () => {
maps.event.addDomListener(window, "resize", () => {
map.fitBounds(bounds);
});
});
};
// Return map bounds based on list of places
const getMapBounds = (map, maps, pins) => {
const bounds = new maps.LatLngBounds();
pins.forEach((pin) => {
bounds.extend(new maps.LatLng(pin[1], pin[0]));
});
return bounds;
};
return ( <
div >
<
div style = {
{
height: "100vh",
width: "100%"
}
} >
<
GoogleMapReact bootstrapURLKeys = {
{
key: AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk
}
}
defaultCenter = {
tallinn.center
}
defaultZoom = {
tallinn.zoom
}
onGoogleApiLoaded = {
({
map,
maps
}) => apiIsLoaded(map, maps, latLgn)
}
yesIWantToUseGoogleMapApiInternals >
{
latLgn.map((item, index) => ( <
div lat = {
item[1]
}
lng = {
item[0]
}
key = {
index
} >
</div>
))
} </GoogleMapReact>
</div>
</div>
);
}
export default Gmap
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I have a problem with centralizing the map I am rendering.
although I have a state with the "lat" and "lng" as stated in the docs still, when I run the app with npm start or refreshing the page, it will centre itself somewhere in the ocean.\
PS. I will paste my "map" component only.
import React, { useState } from "react";
import GoogleMapReact from "google-map-react";
export default function GMap() {
const [latLgn, setLatLgn] = useState([{
lng: 24.7536,
lat: 59.437
},
{
lng: 24.7303,
lat: 59.4393
},
{
lng: 24.7387,
lat: 59.4497
},
]);
const [tallinn] = useState({
center: { // where i want to be centerd
lng: 24.7536,
lat: 59.437,
},
zoom: 10,
});
// Fit map to its bounds after the api is loaded
const apiIsLoaded = (map, maps, latlgn) => {
// Get bounds by our latlgn
const bounds = getMapBounds(map, maps, latlgn);
// Fit map to bounds
map.fitBounds(bounds);
// Bind the resize listener
bindResizeListener(map, maps, bounds);
};
// Re-center map when resizing the window
const bindResizeListener = (map, maps, bounds) => {
maps.event.addDomListenerOnce(map, "idle", () => {
maps.event.addDomListener(window, "resize", () => {
map.fitBounds(bounds);
});
});
};
// Return map bounds based on list of places
const getMapBounds = (map, maps, pins) => {
const bounds = new maps.LatLngBounds();
pins.forEach((pin) => {
bounds.extend(new maps.LatLng(pin[1], pin[0]));
});
return bounds;
};
return (
<div>
<div style={{ height: "100vh", width: "100%" }}>
<GoogleMapReact
bootstrapURLKeys={{key: AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk }}
defaultCenter={tallinn.center}
defaultZoom={tallinn.zoom}
onGoogleApiLoaded={({ map, maps }) => apiIsLoaded(map, maps, latLgn)}
yesIWantToUseGoogleMapApiInternals
>
{latLgn.map((item, index) => (
<div lat={item[1]} lng={item[0]} key={index}< </div>
))}
</GoogleMapReact>
</div>
</div>
);
}
ps. let me know if I should provide more information
UPDATE
I have created a sample project here.
I checked your code and I noticed a couple of things.
First, in your getMapBounds function, the bounds returned are null. This is because the values of pin[1] and pin[0] are undefined. This might be the reasoon why the map is centering in the middle of the ocean like this as this is the center of the world and coordinates are 0,0. You must use pin.lat and pin.lng instead so that it will correctly populate the value for bounds.
Second, it seems that you would like to put markers on the coordinates of your latLgn. To achieve this, you can follow the AnyReactComponent function as mentioned in the google-map-react docs instead of putting a div directly inside the latLgn.map.
Lastly, inside your latLgn.map, you must not use item[1] and item[0] as they are also both undefined instead use item.lat and item.lng.
Here's the code snippet for my working code:
import React, { useState } from "react";
import "./style.css"
import GoogleMapReact from "google-map-react";
const AnyReactComponent = ({ text }) => <div>{text}</div>;
export default function GMap() {
const [latLgn, setLatLgn] = useState([{
lng: 24.7536,
lat: 59.437
},
{
lng: 24.7303,
lat: 59.4393
},
{
lng: 24.7387,
lat: 59.4497
},
]);
const [tallinn] = useState({
center: { // where i want to be centerd
lng: 24.7536,
lat: 59.437,
},
zoom: 10,
});
// Fit map to its bounds after the api is loaded
const apiIsLoaded = (map, maps, latlgn) => {
// Get bounds by our latlgn
const bounds = getMapBounds(map, maps, latlgn);
// Fit map to bounds
map.fitBounds(bounds);
// Bind the resize listener
bindResizeListener(map, maps, bounds);
};
// Re-center map when resizing the window
const bindResizeListener = (map, maps, bounds) => {
maps.event.addDomListenerOnce(map, "idle", () => {
maps.event.addDomListener(window, "resize", () => {
map.fitBounds(bounds);
});
});
};
// Return map bounds based on list of places
const getMapBounds = (map, maps, pins) => {
const bounds = new maps.LatLngBounds();
pins.forEach((pin) => {
bounds.extend(new maps.LatLng(pin.lat, pin.lng));
console.log(pin[0])
});
return bounds;
};
return (
<div>
<div style={{ height: "100vh", width: "100%" }}>
<GoogleMapReact
bootstrapURLKeys={{key: "YOUR_API_KEY" }}
defaultCenter={tallinn.center}
defaultZoom={tallinn.zoom}
onGoogleApiLoaded={({ map, maps }) => apiIsLoaded(map, maps, latLgn)}
yesIWantToUseGoogleMapApiInternals
>
{latLgn.map((item, index) => (
<AnyReactComponent lat={item.lat} lng={item.lng} key={index} text={"(" +item.lat + "," + item.lng +")"}> </AnyReactComponent>
))}
</GoogleMapReact>
</div>
</div>
);
}
I also noticed your question in the comment section. You can use online ides like stackblitz to provide an sscce of your code and just remove the API key. You can put a note in your question that you need to put API key to see how the code works. You can refer to my working code above.

React with Google Maps Api, how to recenter map

I'm using react and using the map as a functional component. (tbh I'm still unsure as to when to use classes v. functions when it comes to classes). however my main issue is that I'm using the google Maps API to present a map and I'm trying to center a map on the users current location. also, I wanted it to update as they walked around so I was just going to use a set interval function to set a timer of when it updates.
I thought that the navigator would be my best bet. Although I can't seem to find a proper function to update the center property after initialization.
I'll mark where I think the function should go.
Here's the documentation I've been looking at:
https://tomchentw.github.io/react-google-maps/#googlemap
function MapContainer() {
const [currentLoc,setCurrentLoc] = useState(
{
lat: 42.331429,
lng: -83.045753
}
)
function setLocation() {
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(
(position) => {
setCurrentLoc(position.coords.latitude,position.coords.longitude)
}
)
}
}
return (
<LoadScript
googleMapsApiKey="Api key"
>
<GoogleMap
//THIS IS WHERE YOU STYLLLLLEEEE
//also where you set what is visible with the controls
options= {{
styles:mapStyles['hide'],
mapTypeControl:false,
disableDefaultUI:true,
draggable:true,
zoomControl:true
}}
id="44b929060bf5f087"
mapContainerStyle=
{{
height: "86.5vh",
width: "100%",
stylers: mapStyles['hide'],
draggable: false
}}
center={{
lat: 44.331429,
lng: -83.045753
}}
zoom={10}
>
{
setInterval((props) => {
var long;
var lati;
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(
(position) => {
lati = position.coords.latitude;
long = position.coords.longitude;
}
)
};
//here is where i'd set the center if i had a function i could do it with
}, 2000)
}
</GoogleMap>
</LoadScript>
)
}
export default MapContainer;
I can't access the documentation link of react-google-maps library. You can use the #react-google-maps/api library since this is a rewrite of the react-google-maps and is more maintained.
For your use case, you can set the value of your center in a state and update it in the setinterval function. This way, each time the state value of the center changes, the center also changes. Please see this sample code and code snippet below:
import React from "react";
import { GoogleMap, LoadScript } from "#react-google-maps/api";
const containerStyle = {
width: "400px",
height: "400px",
};
function MyComponent() {
const [map, setMap] = React.useState(null);
const [currentLoc, setCurrentLoc] = React.useState({
lat: 42.331429,
lng: -83.045753,
});
const onLoad = React.useCallback(function callback(map) {
setMap(map);
setInterval((props) => {
console.log("refreshed");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
setCurrentLoc({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
});
}
}, 2000);
}, []);
return (
<LoadScript googleMapsApiKey="YOUR_API_KEY">
<GoogleMap
mapContainerStyle={containerStyle}
center={{ lat: currentLoc.lat, lng: currentLoc.lng }}
zoom={10}
onLoad={onLoad}
>
{/* Child components, such as markers, info windows, etc. */}
<></>
</GoogleMap>
</LoadScript>
);
}
export default React.memo(MyComponent);

Can I export values from an arrow function in ReactJS?

I'm trying to use pass lng lat variables to the a google maps component from a google's geocode API, however since the geocode function is an arrow function I'm unable to use the values outside of this function. Is there any way to fix this? I need to be able to use the constants lat and lng from the geocode function and pass them to the lat and lang properties in the MapWithMarker constant
Geocode.fromAddress("5th Avenue New York").then(
response => {
const{ lat, lng } = response.results[0].geometry.location;
},
error => {
console.error(error);
}
);
const MapWithAMarker = withGoogleMap(props =>
<GoogleMap
defaultZoom={0}
defaultCenter={{ lat: lat, lng: lng }}
>
<Marker
position={{ lat: lat, lng: lng }}
/>
</GoogleMap>
);
./src/components/dashboard/ProductDetails.js
Line 107: 'lat' is not defined no-undef
Line 107: 'lng' is not defined no-undef
Line 110: 'lat' is not defined no-undef
Line 110: 'lng' is not defined no-undef
One way of doing this is
var MapWithAMarker;
Geocode.fromAddress("5th Avenue New York").then(
response => {
const{ lat, lng } = response.results[0].geometry.location;
MapWithAMarker = withGoogleMap(props =>
<GoogleMap
defaultZoom={0}
defaultCenter={{ lat: lat, lng: lng }}
>
<Marker
position={{ lat: lat, lng: lng }}
/>
</GoogleMap>
);
}
)
.catch(err => console.log(err));
And then you do use it like
if( MapWithAMarker ){
// do whatever you want;
}
You can cache them such as:
const MyMapComponent = function(props) {
const [position, setPosition] = React.useState();
React.useEffect(() => {
Geocode.fromAddress("5th Avenue New York").then(
response => {
setPosition(response.results[0].geometry.location);
},
error => {
console.error(error);
}
);
}, [])
if (!position) {
return null;
}
return <MapWithAMarker {...props} lat={position.lat} lng={position.lng} />
}
const MapWithAMarker = withGoogleMap(props =>
const
<GoogleMap
defaultZoom={0}
defaultCenter={{ lat: props.lat, lng: props.lng }}
>
<Marker
position={{ lat: props.lat, lng: props.lng }}
/>
</GoogleMap>
);
And now you can use MyMapComponent as a decorator of MapWithAMarker.

Resources