I am trying create a map using google maps v3 api. I have found the below code over internet and I want to show the latitude and logitude in map window instead of address.
I created a tiny component to illustrate with React
. Although, it's the same API
. I thought this might be helpful.
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { GoogleApiWrapper } from 'google-maps-react';
const SearchLocation = ({ google }) => {
const [inputData, setInputData] = useState('');
const handleChange = ({ target: { value } }) => {
if (value) {
setInputData(value);
const autoCompleteService = new google.maps.places.AutocompleteService();
autoCompleteService.getPlacePredictions(
{ input: value },
(predictions, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
// update prediction, so that user can click on the predicted address
const updatePredictions = (predictions) => {};
// or get the coordinate of one prediction
if (predictions.length > 0) {
geoCodeLocation(predictions[0]);
}
}
}
);
}
};
const geoCodeLocation = (suggestion) => {
const placeId = suggestion.place_id;
const GeoCoder = new google.maps.Geocoder();
GeoCoder.geocode({ placeId }, (response) => {
const lattitude = response[0].geometry.location.lat();
const longitude = response[0].geometry.location.lng();
const coordinates = [longitude, lattitude];
// save coordinate and suggestion
const selectLocation = ({ coordinates, suggestion }) => {};
});
};
return (
{/* handle suggestion */}
);
};
export default GoogleApiWrapper({
apiKey: process.env.GOOGLE_API_KEY,
v: '3'
})(SearchLocation);
SearchLocation.defaultProps = {};
SearchLocation.propTypes = {
google: PropTypes.shape({}).isRequired,
};