【发布时间】:2020-09-02 13:17:41
【问题描述】:
我正在遵循google maps 的官方指南,并尝试按照以下方式在我的 React 应用中实现它:
import React, { Component } from 'react';
import './styles/locationInput.css';
export class locationInput extends Component {
render() {
const { values, handleChange } = this.props;
function initAutocomplete() {
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
var markers = [];
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
markers.push(new google.maps.Marker({
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
});
}
initAutocomplete()
return (
<input
defaultValue={values.CollegeName}
onChange={handleChange('CollegeName')}
id="pac-input"
className="controls"
type="text"
placeholder="Search Box"
/>
);
}
}
export default locationInput;
我在
index.html中有初始<script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete"
async defer></script>
但我收到此错误
编译失败
./src/public/form/lib-component/locationInput.js
Line 10:24: 'google' is not defined no-undef
Line 25:23: 'google' is not defined no-undef
Line 33:17: 'google' is not defined no-undef
Line 34:19: 'google' is not defined no-undef
Line 35:19: 'google' is not defined no-undef
Line 36:23: 'google' is not defined no-undef
Line 39:22: 'google' is not defined no-undef
Search for the keywords to learn more about each error.
我的问题是,当我尝试以普通的 html 和 javascript 实现此代码时,它完美地工作但没有反应,所以我怎样才能让它在这里工作,我如何指定 google 在这里的含义?
【问题讨论】:
-
尝试新的 window.google.maps
-
另外,还有一个很好的 React 组件:github.com/hibiken/react-places-autocomplete
-
@ertemishakk 我不明白你实施
window.google.maps是什么意思,你能详细说明一下吗... -
在您的代码中将
new google.maps替换为new window.google.maps。 -
@LáďaDurchánek 我试过了,但我在将其他组件的状态集成到它时遇到了问题,而且它看起来不像 gmap api 的文档那么好
标签: reactjs google-maps google-maps-api-3 autocomplete