javascript - 如何使用 google-maps-react 居中和放大多个标记?
问题描述
我发现这个堆栈溢出链接是用 vanilla javascript 完成的,但是它使用了我在google-maps-react API中看不到的方法,比如LatLngBounds
and bounds.extend()
,但它确实有maps.fitbounds()
.
我是否错过了对 API 的误读,或者这些方法在 google-maps-react 上真的不存在。如果不是,那么我将如何在地图上的多个标记上进行居中和放大。
解决方案
我认为 google-maps-react 没有本地方式来完成此操作,您必须直接通过onGoogleApiLoaded
prop 使用 google maps api。
这个例子中的花絮这个例子:
// Fit map to its bounds after the api is loaded
const apiIsLoaded = (map, maps, places) => {
// Get bounds by our places
const bounds = getMapBounds(map, maps, places);
// Fit map to bounds
map.fitBounds(bounds);
// Bind the resize listener
bindResizeListener(map, maps, bounds);
};
class Main extends Component {
constructor(props) {
super(props);
this.state = {
places: [],
};
}
componentDidMount() {
fetch('places.json')
.then((response) => response.json())
.then((data) => this.setState({ places: data.results }));
}
render() {
const { places } = this.state;
return (
<>
{!isEmpty(places) && (
<GoogleMap
defaultZoom={10}
defaultCenter={LOS_ANGELES_CENTER}
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={({ map, maps }) => apiIsLoaded(map, maps, places)}
>
{places.map((place) => (
<Marker
key={place.id}
text={place.name}
lat={place.geometry.location.lat}
lng={place.geometry.location.lng}
/>
))}
</GoogleMap>
)}
</>
);
}
}
export default Main;
推荐阅读
- java - 当我构建 gradle 时,这是什么错误?
- javascript - 嘲笑一个函数,但开玩笑地调用原始函数
- javascript - 三角形未显示在页面上,代码适用于所有其他形状
- javascript - 我有 json 对象我想找到具有父索引值的 id
- regex - 正则表达式脚本查找和替换
- javascript - 尝试在第一次单击后保留的表格中创建下拉菜单
- php - 如何在__soapcall()函数中的php中发送soap请求中的参数
- c# - EF Core 开销?
- asp.net-web-api - 添加对项目的引用时引用无效或不受支持
- brightway - 如何使用 Brightway 参数化现有的交换