首页 > 解决方案 > 无法使用 ReactJS 重新渲染 Google 地图

问题描述

我正在尝试根据位置(城市)重新渲染谷歌地图。我在输入类型中输入了城市,但没有任何反应。谁能帮我这个?我已经尝试了很多东西,但没有任何反应。问候,

https://pastebin.pl/view/e31aeb6a [在此处输入链接描述][1]

标签: javascriptreactjsmaps

解决方案


您可能正在寻找类似的东西您将使用 Geocoding API 从您的输入中对地址进行地理编码,然后一旦地理编码,它将获取坐标并使用 Maps JavaScript API 将其绘制到您的地图上。

您可能还想使用 Maps JavaScript API 检查 Places Autocomplete,它会在其中提供有关您正在搜索的地址的建议,然后在地图上呈现您选择的地点。

请注意,如果您想使用 Google Maps API,您需要使用 API 密钥,并且这些 API 的使用会相应收费

是我在 React 上实现它的方法。下面的代码片段:

import React from 'react';
import ReactDOM from 'react-dom';
import './style.css';

var map;
const API_KEY = "PUT_API_KEY_HERE";
class GeocodingApp extends React.Component {
  constructor(props) {
    super(props);
    this.renderMap = this.renderMap.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleClick = this.handleClick.bind(this);
    this.state = {
      input: ""
    };
  }

  componentDidMount() {

       if (!window.google) {
            const script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = `https://maps.googleapis.com/maps/api/js?key=` + API_KEY + `&libraries=geometry,places`;
            script.id = 'googleMaps';
            script.async = true;
            script.defer = true;
            document.body.appendChild(script);
            script.addEventListener('load', e => {
                this.renderMap()
            })
        } else {
            this.renderMap()
        }
    
  }

  renderMap() {
    const coords = { lat: 41.375885, lng: 2.177813 };
    const el = document.getElementById("map");

    if (el) {
      map = new google.maps.Map(el, {
        zoom: 16,
        center: {
          lat: coords.lat,
          lng: coords.lng
        }
      });

      return map;
    } else {
      return null;
    }
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === "checkbox" ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  handleClick(event) {
    const geocoder = new google.maps.Geocoder();
    this.codeAddress(geocoder);
    event.preventDefault();
  }

 
//Handles Geocoding part
  codeAddress(geocoder) {
    var address = this.state.input;
    geocoder.geocode({ address: address }, function(results, status) {
      if (status === "OK") {
        //'results[0].geometry.location' is the coordinates of the address you want to find
        map.setCenter(results[0].geometry.location);
      } else {
        return null;
      }
    });
  }

  render() {
    return (
      <div >
        <h1>ADD YOUR API KEY TO MAKE IT WORKIN</h1>
        <input
          id="input"
          name="input"
          value={this.state.input}
          onChange={this.handleInputChange}
        />
        <button id="submit" onClick={this.handleClick}>
          {" "}
          Search
        </button>
        <div id="map"  />
        
      </div>
    );
  }
}

 ReactDOM.render(<GeocodingApp />, document.getElementById("app"));

推荐阅读