I’m using google-maps-react library for maps in my react application, and I’m adding search address functionality in my application and facing CORS error.
Autocomplete.js
import React, { Component } from 'react';
import styled from 'styled-components';
const Wrapper = styled.div`
position: relative;
align-items: center;
justify-content: center;
width: 100%;
padding: 20px;
text-align:center;
`;
class AutoComplete extends Component {
constructor(props) {
super(props);
this.clearSearchBox = this.clearSearchBox.bind(this);
}
componentDidMount({ map, mapApi } = this.props) {
const options = {
// restrict your search to a specific type of result
types: ['address'],
// restrict your search to a specific country, or an array of countries
// componentRestrictions: { country: ['gb', 'us'] },
};
this.autoComplete = new mapApi.places.Autocomplete(
this.searchInput,
options,
);
this.autoComplete.addListener('place_changed', this.onPlaceChanged);
this.autoComplete.bindTo('bounds', map);
}
componentWillUnmount({ mapApi } = this.props) {
mapApi.event.clearInstanceListeners(this.searchInput);
}
onPlaceChanged = ({ map, addplace } = this.props) => {
const place = this.autoComplete.getPlace();
if (!place.geometry) return;
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
addplace(place);
this.searchInput.blur();
};
clearSearchBox() {
this.searchInput.value = '';
}
render() {
return (
<Wrapper>
<input
className="search-input"
ref={(ref) => {
this.searchInput = ref;
}}
type="text"
onFocus={this.clearSearchBox}
placeholder="Enter a location"
/>
</Wrapper>
);
}
}
export default AutoComplete;
MyGoogleMap.js
const MyGoogleMap = () => {
const [apiReady, setApiReady] = useState(false);
const [map, setMap] = useState(null);
const [mapApi, setMapApi] = useState(null);
const [address, setAddress] = useState();
const [zoom, setZoom] = useState();
const [center, setCenter] = useState([]);
const [lat, setLat] = useState();
const [lng, setLng] = useState();
const [places, setPlaces] = useState();
const [draggable, setDraggable] = useState();
const setCurrentLocation = () => {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(position => {
console.log('position.coords: ', position.coords.longitude);
console.log("[position.coords.latitude, position.coords.longitude]: ", [position.coords.latitude, position.coords.longitude])
setCenter([position.coords.latitude, position.coords.longitude]);
setLat(position.coords.latitude);
setLng(position.coords.longitude);
});
}
};
useEffect(() => {
setCurrentLocation();
}, []);
const handleApiLoaded = (map, maps) => {
console.log('map, maps: ', map, maps);
// use map and maps objects
if (map && maps) {
setApiReady(true);
setMap(map);
setMapApi(maps);
}
};
const _generateAddress = () => {
const geocoder = new mapApi.Geocoder();
geocoder.geocode({ location: { lat: lat, lng: lng } }, (results, status) => {
console.log(results);
console.log(status);
if (status === 'OK') {
if (results[0]) {
setZoom(12);
setAddress(results[0].formatted_address);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
};
const onMarkerInteraction = (childKey, childProps, mouse) => {
setDraggable(true);
setLat(mouse.lat);
setLng(mouse.lng);
};
const onMarkerInteractionMouseUp = (childKey, childProps, mouse) => {
setDraggable(true);
_generateAddress();
};
const _onChange = ({ center, zoom }) => {
setZoom(zoom);
setCenter(center);
};
const _onClick = value => {
setLat(value.lat);
setLng(value.lng);
};
const addPlace = place => {
setPlaces([place]);
setLat(place.geometry.location.lat());
setLng(place.geometry.location.lng());
_generateAddress();
};
return (
<div style={{ height: '442px', width: '100%' }}>
{apiReady && <Autocomplete map={map} mapApi={mapApi} addplace={addPlace} />}
<GoogleMapReact
zoom={4}
center={center}
bootstrapURLKeys={{
key: 'API_KEY',
libraries: ['places', 'geometry'],
}}
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={({ map, maps }) =>
handleApiLoaded(map, maps)
}
></GoogleMapReact>
</div>
);
}
I’m following this article to integrate Google Maps with search