Javascript 在React中使用Google Place自动完成API

Javascript 在React中使用Google Place自动完成API,javascript,reactjs,google-maps-api-3,Javascript,Reactjs,Google Maps Api 3,我想在react组件中有一个自动完成的位置搜索栏,但不知道如何实现它。报告说要包括 <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script> 在一个HTML文件中,然后有一个指向元素的初始化函数——我该如何使用我的react组件/JSX来实现这一点?我假设我

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

<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;
从“React”导入React;
进口”https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=places&callback=initMap";
常量搜索栏=()=>(
//我想要谷歌自动完成的地方
);
导出默认搜索栏;

通过静态
导入加载Google地图API

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

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

  • 通过/public/index.html文件参考Google Maps API JS库:
  • 或者动态加载JS资源,例如使用
现在关于
SearchBar
组件,下面的示例演示了如何基于

从“React”导入React;
/*全球谷歌*/
类SearchBar扩展了React.Component{
建造师(道具){
超级(道具);
this.autocompleteInput=React.createRef();
this.autocomplete=null;
this.handlePlaceChanged=this.handlePlaceChanged.bind(this);
}
componentDidMount(){
this.autocomplete=new google.maps.places.autocomplete(this.autocompleteInput.current,
{“类型”:[“地理编码”]});
this.autocomplete.addListener('place\u changed',this.handlePlaceChanged);
}
手部位置已更改(){
const place=this.autocomplete.getPlace();
此.props.onPlaceLoaded(位置);
}
render(){
返回(
);
}
}

在为注册表单制作自定义地址自动完成时遇到了一些问题

// index.html imports the google script via script tag  ie: <script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=places"></script>


import {useState, useRef, useEffect } from 'React'

function AutoCompleteInput(){

const [predictions, setPredictions] = useState([]);
const [input, setInput] = useState('');
const [selectedPlaceDetail, addSelectedPlaceDetail] = useState({})
const predictionsRef = useRef();


useEffect(
()=>{
      try {
        autocompleteService.current.getPlacePredictions({ input }, predictions => {
          setPredictions(predictions);
        });
      } catch (err) {
       // do something
      }
    }
}, [input])

const handleAutoCompletePlaceSelected = placeId=>{
 if (window.google) {
      const PlacesService = new window.google.maps.places.PlacesService(predictionsRef.current);
      try {
        PlacesService.getDetails(
          {
            placeId,
            fields: ['address_components'],
          },
         place => addSelectedPlaceDetail(place)
        );
      } catch (e) {
        console.error(e);
      }
    }
}

return (
  <>
   <input onChange={(e)=>setInput(e.currentTarget.value)}
    <div ref={predictionsRef}
     { predictions.map(prediction => <div onClick={ ()=>handleAutoCompletePlaceSelected(suggestion.place_id)}> prediction.description </div> )
   }
   </div>
  <>
 )
}
//index.html通过脚本标记ie导入google脚本:
从“React”导入{useState,useRef,useffect}
函数自动完成输入(){
const[predictions,setPredictions]=useState([]);
const[input,setInput]=useState(“”);
常量[selectedPlaceDetail,addSelectedPlaceDetail]=useState({})
const predictionsRef=useRef();
使用效果(
()=>{
试一试{
autocompleteService.current.getPlacePredictions({input},predictions=>{
设定预测(预测);
});
}捕捉(错误){
//做点什么
}
}
},[输入])
const handleautompleteplaceselected=placeId=>{
if(window.google){
const PlacesService=new window.google.maps.places.PlacesService(predictionsRef.current);
试一试{
PlacesService.getDetails(
{
placeId,
字段:['address_components'],
},
地点=>addSelectedPlaceDetail(地点)
);
}捕获(e){
控制台错误(e);
}
}
}
返回(
setInput(e.currentTarget.value)}
handleAutoCompletePlaceSelected(suggestion.place\u id)}>prediction.description)
}
)
}
因此,基本上,您设置了自动完成调用,并在您的本地州返回预测结果

从那里,用一个click处理程序映射并显示结果,该处理程序将对places服务执行后续请求,该服务可以访问完整地址对象或任何您想要的字段的getDetails方法


然后将该响应保存到您的本地州,然后离开

当我这样做时,我得到的错误是
google'未定义为no undef
。根据演示,我将GoogleAPI脚本(带有我自己的密钥)放在public/index.html文件中,但它仍然无法识别google。不知怎的,它不是全局的?@Adam.V,你可能忘了把
/*global google*/
放在文件的顶部。或者可以利用。它还包含了为什么会发生此错误的解释!我看到灰色文本,认为这只是一个评论。我不知道它在js中有任何作用。
// index.html imports the google script via script tag  ie: <script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=places"></script>


import {useState, useRef, useEffect } from 'React'

function AutoCompleteInput(){

const [predictions, setPredictions] = useState([]);
const [input, setInput] = useState('');
const [selectedPlaceDetail, addSelectedPlaceDetail] = useState({})
const predictionsRef = useRef();


useEffect(
()=>{
      try {
        autocompleteService.current.getPlacePredictions({ input }, predictions => {
          setPredictions(predictions);
        });
      } catch (err) {
       // do something
      }
    }
}, [input])

const handleAutoCompletePlaceSelected = placeId=>{
 if (window.google) {
      const PlacesService = new window.google.maps.places.PlacesService(predictionsRef.current);
      try {
        PlacesService.getDetails(
          {
            placeId,
            fields: ['address_components'],
          },
         place => addSelectedPlaceDetail(place)
        );
      } catch (e) {
        console.error(e);
      }
    }
}

return (
  <>
   <input onChange={(e)=>setInput(e.currentTarget.value)}
    <div ref={predictionsRef}
     { predictions.map(prediction => <div onClick={ ()=>handleAutoCompletePlaceSelected(suggestion.place_id)}> prediction.description </div> )
   }
   </div>
  <>
 )
}