【发布时间】:2020-11-04 07:22:18
【问题描述】:
使用 Google Maps Api 做出反应,我正在附近搜索以查找和放置篮球场的别针。首次加载地图时,它会工作并放置图钉:
loadMap() {
if (this.props && this.props.google) {
// checks if google is available
const { google } = this.props;
const maps = google.maps;
const mapRef = this.refs.map;
// reference to the actual DOM element
const node = ReactDOM.findDOMNode(mapRef);
let { zoom } = this.props;
const { lat, lng } = this.state.currentLocation;
const center = new maps.LatLng(lat, lng);
const mapConfig = Object.assign(
{},
{
center: center,
zoom: zoom,
options: options
}
);
// maps.Map() is constructor that instantiates the map
this.map = new maps.Map(node, mapConfig);
// This is the function to display all the markers
this.searchCourts(); // This works properly
// This one below fails
this.props.google.maps.event.addListener(this.map, "dragend", function() {
this.newSearchonDrag() //Error: this.NewSearchonDrag is not a function ????
})
}
}
这里是 searchCourts 函数:
searchCourts = () => {
const map = this.props.google.maps.Map
const { google } = this.props;
const maps = google.maps;
const request = {
location: this.map.getCenter(),
radius: '50000',
name: ['basketball court']
}
const service = new google.maps.places.PlacesService(this.map);
// ACTUAL SEARCH FOR COURTS
service.nearbySearch(request, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
});
// MARKERS TO BE DROPPED
const createMarker= (place) => {
let marker = new this.props.google.maps.Marker({
map: this.map,
position: place.geometry.location,
title: place.name
});
let infowindow = new this.props.google.maps.InfoWindow({
name: place.name,
vicinity: place.vicinity
});
marker.addListener("click", function() {
let contentString = `<div id="infowindow">` + place.name + `<br>` + place.vicinity + `</div> `
infowindow.setContent(contentString)
infowindow.open(this.map, marker)
})
}
}
这在地图加载时有效,并且我的 newSearchonDrag() 与 searchCourts() 基本相同,但是当它被拖动时我能够找到地图的 newCenter。
在我看来问题是范围问题...在我的 dragend 事件中...我无法调用 Map 类中的任何函数...似乎每次拖动发生时都可以调用 searchCourts() 但是我不知道如何在事件中调用它。
【问题讨论】:
-
所以我有一个 SearchBar 的功能,我在其中放置了一个“this.searchCourts()”并且它起作用了..所以对我来说它似乎确实是一个范围问题..我该怎么做在事件中调用类函数......
标签: javascript reactjs events google-maps-api-3 google-places-api