嗨,我正在创建nextjs应用程序,我在其中使用了谷歌地图反应库中的GoogleMapReact,我想根据新的道具重新渲染我的GoogleMapReact组件
这是我的map.js文件
import GoogleMapReact from 'google-map-react'
import { AsYouType } from 'libphonenumber-js'
import React, { useState, useEffect } from 'react';
const phoneFormat = new AsYouType('US')
const Marker = props => `
<div class="max-w-sm rounded overflow-hidden shadow-lg">
<div class="px-2">
<div class="font-bold text-base mb-2 text-blue-500">
<a href=${"/locations/"+props.id}>
${props.city}
</a>
</div>
<p class="text-dark-400 text-sm">${props.street}</p>
<p class="text-dark-400 text-sm mb-2">
${props.city}, ${props.stateIso}, ${props.countryIso}, ${props.postalCode}
</p>
<p class="text-gray-700 font-medium mb-2">
Phone: <span class="font-light">${phoneFormat.input(props.phone)}</span>
</p>
<p>
<a class="text-blue-500" href="https://www.google.com/maps/dir/'+${props.defaultLat}+','+${props.defaultLng}+'/'+${props.latitude}+','+${props.longitude}+'">
Directions
</a>
</p>
</div>
</div>
`
// Map component should always take in array of LocationSummary object
// ToDo: setting prop types.
export default function Map(props) {
const defaultProps = {
center: {
lat: (typeof(props.latitude) === "undefined" ? 37.0902 : props.latitude),
lng: (typeof(props.longitude) === "undefined" ? 95.7129: props.longitude),
},
zoom: 5
}
function handleApiLoaded(map){
let infowindow = new google.maps.InfoWindow()
props.locations.map((location) => {
let marker = new google.maps.Marker({position: {lat: parseFloat(location.latitude), lng: parseFloat(location.longitude)}, map: map, title: location.name})
marker.addListener('click', function() {
infowindow.close()
infowindow.setContent(Marker(location))
infowindow.open(map, marker)
})
})
}
return (
<div style={{ height: '500px', width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: '123' }}
center={defaultProps.center}
defaultZoom={defaultProps.zoom}
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={({ map }) => handleApiLoaded(map)}
/>
</div>
)
}
这里prop.locations有更新的数组结果,但问题是它没有在我的地图中刷新,有人能建议我如何做到这一点,以便在数据更改时重新渲染我的地图吗??
您使用onGoogleApiLoaded
的方式不对。
通过查看源代码,您可以看到onGoogleApiLoaded
从未被调用过两次:
if (!this_.googleApiLoadedCalled_) {
this_._onGoogleApiLoaded({ map, maps, ref: this_.googleMapDom_ });
this_.googleApiLoadedCalled_ = true;
}
您使用react谷歌地图组件的方式不对。应该是这样的:
<GoogleMapReact
bootstrapURLKeys={{ key: '123' }}
center={defaultProps.center}
defaultZoom={defaultProps.zoom}
>
{ props.locations.map(location => (
<Marker
lat={location.lat}
lng={location.lng}
/>
)) }
</GoogleMapReact>
对于标记和信息窗口,请查看示例