首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

React Google Maps不是在指定lat、long上打开,而是在随机位置打开

React Google Maps是一个用于在React应用中集成Google Maps的开源库。它提供了一组React组件,使开发者能够轻松地在应用中显示地图、标记位置、绘制路径等。

对于指定lat和long打开地图的需求,可以使用React Google Maps提供的组件和API来实现。首先,需要使用<GoogleMapReact>组件来创建一个地图容器,并通过设置center属性来指定地图的中心位置。例如:

代码语言:txt
复制
import React from 'react';
import GoogleMapReact from 'google-map-react';

const Map = () => {
  const center = {
    lat: 40.712776,
    lng: -74.005974
  };

  return (
    <div style={{ height: '400px', width: '100%' }}>
      <GoogleMapReact
        defaultCenter={center}
        defaultZoom={10}
      >
        {/* 在这里添加其他地图元素,如标记、路径等 */}
      </GoogleMapReact>
    </div>
  );
};

export default Map;

在上述代码中,center对象指定了地图的中心位置,其中lat表示纬度,lng表示经度。通过将center对象传递给defaultCenter属性,地图将在指定的位置上打开。

如果需要在随机位置打开地图,可以通过生成随机的经纬度来实现。例如,可以使用Math.random()函数生成0到1之间的随机数,并将其映射到合适的经纬度范围。以下是一个示例:

代码语言:txt
复制
import React from 'react';
import GoogleMapReact from 'google-map-react';

const Map = () => {
  const getRandomCoordinate = () => {
    const minLat = -90;
    const maxLat = 90;
    const minLng = -180;
    const maxLng = 180;

    const lat = Math.random() * (maxLat - minLat) + minLat;
    const lng = Math.random() * (maxLng - minLng) + minLng;

    return {
      lat,
      lng
    };
  };

  const center = getRandomCoordinate();

  return (
    <div style={{ height: '400px', width: '100%' }}>
      <GoogleMapReact
        defaultCenter={center}
        defaultZoom={10}
      >
        {/* 在这里添加其他地图元素,如标记、路径等 */}
      </GoogleMapReact>
    </div>
  );
};

export default Map;

在上述代码中,getRandomCoordinate函数生成一个随机的经纬度,并返回一个包含latlng属性的对象。通过将该对象作为defaultCenter属性的值,地图将在随机位置上打开。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

1分19秒

如何在浏览器Web前端在线编辑PPT幻灯片?

领券