如何使用NextJ加载Google Maps API?
如何使用NextJ加载和使用Google Maps API?
1-如何加载API?我尝试在_document.js中加载它:
import { Html, Head, Main, NextScript } from 'next/document'
import Script from 'next/script'
const source = `https://maps.googleapis.com/maps/api/js?key=${process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}&libraries=places`
const Document = () => {
return (
<Html>
<Head>
<Script type="text/javascript" src={source} strategy="beforeInteractive" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
export default Document
2-您如何引用API?
像:? window.google.maps.places.autocompleteservice()。getPlacePredictions()
,
但是我遇到了一个错误,因为
我也尝试使用NPM库,但似乎没有任何作用。 react-places-autocomplete use-places-autocomplete
How do you load and use the google maps api using Nextjs?
1 - How do you load the api? I've tried to load it in _document.js:
import { Html, Head, Main, NextScript } from 'next/document'
import Script from 'next/script'
const source = `https://maps.googleapis.com/maps/api/js?key=${process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}&libraries=places`
const Document = () => {
return (
<Html>
<Head>
<Script type="text/javascript" src={source} strategy="beforeInteractive" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
export default Document
2 - How do you reference the API?
Something like: ? window.google.maps.places.AutocompleteService().getPlacePredictions()
But I get an error that google is undefined
I have also tried using npm libraries but none seem to work.
react-places-autocomplete
use-places-autocomplete
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Google Maps团队提供了一个快速,有用的教程“ 如何加载maps javaScript javascript react “使用@reack-google-maps/api next.js项目中的包装。下面的代码段来自 repo 由教程的作者链接,@leighhalliday 。
1。如何加载Google Maps JavaScript API
(@reack-google-maps/api )加载映射API)
标记
添加到地图2。如何与place + Google Maps API的添加自动
完成 Google Maps团队提供第二个 tutorial 在地图中搜索 +自动完成,该搜索利用 use-autplaces-autocomplete package。您还可以在示例。
The Google Maps team provides a quick, helpful tutorial "How to load Maps JavaScript API in React" that uses the @react-google-maps/api package in a Next.js project. The code snippet below comes from the repo linked by the tutorial's author, @leighhalliday.
1. How to load the Google Maps JavaScript API
(a React hook provided by @react-google-maps/api that loads the Maps API)
Marker
to the map2. How to add Autocomplete with the Places + Google Maps API's
The Google Maps team provide a second tutorial to implement search + autocomplete in your map that leverages the use-places-autocomplete package. You can also find the full code in @leighhalliday's repo example.