javascript - 在 React 中使用 Google Place Autocomplete API

标签 javascript reactjs google-maps-api-3

我想在我的 react 组件中有一个自动完成位置搜索栏,但不知道我将如何实现它。 documentation说包括

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>

在 HTML 文件中,然后有一个指向元素的初始化函数——我将如何使用我的 React 组件/JSX 执行此操作?我想我必须导入 api 链接,但我不知道从那里去哪里。

import React from 'react';
import "https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=places&callback=initMap";

const SearchBar = () => (   
    <input type="text" id="search"/> //where I want the google autocomplete to be
);

export default SearchBar;

最佳答案

通过静态加载 Google Maps API import :

import "https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=places&callback=initMap";

不受支持,您需要为此考虑不同的选项:

  • 通过/public/index.html 文件引用 Google Maps API JS 库: <script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=places"></script>
  • 动态加载JS资源,例如使用this library

现在关于 SearchBar组件,下面的示例演示了如何基于 this official example 实现一个简单版本的 Place Autocomplete(不依赖于 Google Map 实例)

import React from "react";
/* global google */


class SearchBar extends React.Component {
  constructor(props) {
    super(props);
    this.autocompleteInput = React.createRef();
    this.autocomplete = null;
    this.handlePlaceChanged = this.handlePlaceChanged.bind(this);
  }

  componentDidMount() {
    this.autocomplete = new google.maps.places.Autocomplete(this.autocompleteInput.current,
        {"types": ["geocode"]});

    this.autocomplete.addListener('place_changed', this.handlePlaceChanged);
  }

  handlePlaceChanged(){
    const place = this.autocomplete.getPlace();
    this.props.onPlaceLoaded(place);
  }



  render() {
    return (
        <input ref={this.autocompleteInput}  id="autocomplete" placeholder="Enter your address"
         type="text"></input>
    );
  }
}

关于javascript - 在 React 中使用 Google Place Autocomplete API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52907859/

相关文章:

javascript - 如何使用CSS将嵌套元素设置到屏幕边缘

javascript - Flot 从一点到另一点设置一条垂直线的动画

reactjs - npm karma phantomJS undefined 不是构造函数

javascript - 在 Google Maps V3 中获取 GeoJSON 数据层的属性

javascript - 如何使 JavaScript 文件路径相对于当前文件目录?

javascript - 如何使部分透明的 .png 下方的 <div> 保持可滚动?

reactjs - 如何用 React 组件替换 Markdown 渲染的 HTML 标签?

html - ReactJS 的样式问题

google-maps - Google Maps v3 getBounds超出了 map 上可见的范围

javascript - google.maps.Polyline - 如何获得透明/不可见的折线?