【问题标题】:React-Google-Maps API: How to search current location for a search result?React-Google-Maps API:如何在当前位置搜索搜索结果?
【发布时间】:2021-03-31 14:47:52
【问题描述】:

我正在尝试构建与 Airbnb 上类似的地图,您可以在拖动地图时查看地点标记。我想在地图上使用 Google Places API 搜索“治疗中心”并放置标记。

我一直在使用新的、重写的 @react-google-maps/api。到目前为止,我能够创建一个搜索框和一个自动完成功能并获得它们的纬度和经度,但两者都只提供特定的位置而不是最相似的搜索(例如,如果你在谷歌地图上搜索 Taco Bell,它会显示为您附近的几个选择)。下面的代码显示了一个带有搜索框的地图:

import { GoogleMap, LoadScript, Marker, StandaloneSearchBox, Autocomplete } from '@react-google-maps/api';

class HeaderMap extends Component {
  constructor (props) {
    super(props)

    this.autocomplete = null

    this.onLoad = this.onLoad.bind(this)
    this.onPlaceChanged = this.onPlaceChanged.bind(this)

    this.state = {
      currentLocation: {lat: 0, lng: 0},
      markers: [],
      zoom: 8
    }
  }
  

  componentDidMount() {
    navigator?.geolocation.getCurrentPosition(({coords: {latitude: lat, longitude: lng}}) => {
      const pos = {lat, lng}
      this.setState({currentLocation: pos})  
    })
  }

  onLoad (autocomplete) {
    console.log('autocomplete: ', autocomplete)

    this.autocomplete = autocomplete
  }


  onPlaceChanged() {
    if (this.autocomplete !== null) {
      let lat = this.autocomplete.getPlace().geometry.location.lat()
      let long = this.autocomplete.getPlace().geometry.location.lat()
    } else {
      console.log('Autocomplete is not loaded yet!')
    }
  }

  render() {
    return (
      <LoadScript
        googleMapsApiKey="API_KEY_HERE"
        libraries={["places"]}
      >
        <GoogleMap
          id='search-box-example'
          mapContainerStyle={containerStyle}
          center={this.state.currentLocation}
          zoom={14}
          // onDragEnd={search for centers in current location}
        >
          <Marker key={1} position={this.state.currentLocation} />
          <Autocomplete
            onLoad={this.onLoad}
            onPlaceChanged={this.onPlaceChanged}
          >
            <input
              type="text"
              placeholder="Customized your placeholder"
              style={inputStyles}
            />
          </Autocomplete>
        </GoogleMap>
      </LoadScript>
    );
  }
}

如何自动搜索位置的边界并根据关键字获取每个结果的经纬度?感谢您的帮助!

【问题讨论】:

    标签: reactjs google-maps-api-3 react-google-maps


    【解决方案1】:

    在您当前的代码中,您似乎正在使用由库预编码的Autocomplete,以具有Places Autocomplete 的功能。您可以使用StandaloneSearchBox 来实现您的用例,因为它正在实现Places Searchbox,它返回一个包含地点和预测搜索词的选择列表。

    下面是code sample和代码sn-p:

    /*global google*/
    import React from "react";
    
    import { GoogleMap, StandaloneSearchBox, Marker } from "@react-google-maps/api";
    
    let markerArray = [];
    class Map extends React.Component {
      state = {
        currentLocation: { lat: 0, lng: 0 },
        markers: [],
        bounds: null
      };
    
      onMapLoad = map => {
        navigator?.geolocation.getCurrentPosition(
          ({ coords: { latitude: lat, longitude: lng } }) => {
            const pos = { lat, lng };
            this.setState({ currentLocation: pos });
          }
        );
        google.maps.event.addListener(map, "bounds_changed", () => {
          console.log(map.getBounds());
          this.setState({ bounds: map.getBounds() });
        });
      };
    
      onSBLoad = ref => {
        this.searchBox = ref;
      };
    
      onPlacesChanged = () => {
        markerArray = [];
        let results = this.searchBox.getPlaces();
        for (let i = 0; i < results.length; i++) {
          let place = results[i].geometry.location;
          markerArray.push(place);
        }
        this.setState({ markers: markerArray });
        console.log(markerArray);
      };
    
      render() {
        return (
          <div>
            <div id="searchbox">
              <StandaloneSearchBox
                onLoad={this.onSBLoad}
                onPlacesChanged={this.onPlacesChanged}
                bounds={this.state.bounds}
              >
                <input
                  type="text"
                  placeholder="Customized your placeholder"
                  style={{
                    boxSizing: `border-box`,
                    border: `1px solid transparent`,
                    width: `240px`,
                    height: `32px`,
                    padding: `0 12px`,
                    borderRadius: `3px`,
                    boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
                    fontSize: `14px`,
                    outline: `none`,
                    textOverflow: `ellipses`,
                    position: "absolute",
                    left: "50%",
                    marginLeft: "-120px"
                  }}
                />
              </StandaloneSearchBox>
            </div>
            <br />
            <div>
              <GoogleMap
                center={this.state.currentLocation}
                zoom={10}
                onLoad={map => this.onMapLoad(map)}
                mapContainerStyle={{ height: "400px", width: "800px" }}
              >
                {this.state.markers.map((mark, index) => (
                  <Marker key={index} position={mark} />
                ))}
              </GoogleMap>
            </div>
          </div>
        );
      }
    }
    
    export default Map;
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-05
      相关资源
      最近更新 更多