美文网首页
@react-google-maps/api

@react-google-maps/api

作者: 皮神雷卡丘 | 来源:发表于2019-10-16 18:49 被阅读0次

    使用此库所需的两个基本组件是:
    LoadScript-加载Google Maps API脚本,LoadScript 包裹GoogleMap
    GoogleMap-包裹所有其他组件的地图组件

    import React, { Component } from 'react'
    import { GoogleMap, LoadScript } from '@react-google-maps/api'
    
    class MyComponents extends Component {
      render() {
         return (
          <LoadScript
            id="script-loader"
            googleMapsApiKey="YOUR_API_KEY"
            {...other props}
          >
            <GoogleMap
              id='example-map'
              {...other props }
            >
              ...Your map components
            </GoogleMap>
          </LoadScript>
         )
      }
    }
    

    React 16.8+ useLoadScript
    利用useLoadScript钩子,另外还允许指定onLoad,onError和onUnmount回调以及loadElement以便于使用。
    底层React钩子可用更细粒度方法代替笨拙的LoadScriptNext。
    它是LoadScript的替代变体,它通过删除清除例程来解决“未定义google”错误的问题。

    import React from 'react'
    import { GoogleMap, useLoadScript } from '@react-google-maps/api'
    
    const options = {
      zoomControlOptions: {
        position: google.maps.ControlPosition.RIGHT_CENTER // ,
        // ...otherOptopns
      }
    }
    
    function MyComponent() {
      const { isLoaded, loadError } = useLoadScript({
        googleMapsApiKey: "YOUR_API_KEY" // ,
        // ...otherOptions
      })
    
      const renderMap = () => {
        // 如果要访问`window.google`,包装到函数非常有用
        // 例如 设置选项或创建latLng对象,否则它将不可用
        // 如果不需要,可以直接直接渲染
        const onLoad = React.useCallback(
          function onLoad (mapInstance) {
            // do something with map Instance
          }
        )
        return <GoogleMap
          options={options}
          onLoad={onLoad}
        >
          {
            // ...Your map components
          }
        </GoogleMap>
      }
    
      if (loadError) {
        return <div>Map cannot be loaded right now, sorry.</div>
      }
    
      return isLoaded ? renderMap() : <Spinner />
    }
    

    GoogleMap

    center any
    The initial Map center.初始的地图中心。

    clickableIcons boolean | undefined
    When false, map icons are not clickable. A map icon represents a point of interest, also known as a POI. By default map icons are clickable.如果为false,则地图图标不可单击。 地图图标代表一个兴趣点,也称为POI。 默认情况下,地图图标是可单击的。

    extraMapTypes any[] | undefined
    Additional map types to overlay. Overlay map types will display on top of the base map they are attached to, in the order in which they appear in the overlayMapTypes array (overlays with higher index values are displayed in front of overlays with lower index values).要叠加的其他地图类型。 覆盖图类型将以它们在overlayMapTypes数组中出现的顺序显示在它们所附着的基础图的顶部(索引值较高的覆盖图显示在索引值较低的覆盖图的前面)。

    heading number | undefined
    The heading for aerial imagery in degrees measured clockwise from cardinal direction North. Headings are snapped to the nearest available angle for which imagery is available.

    id string | undefined

    mapContainerClassName string | undefined

    mapContainerStyle CSSProperties | undefined

    mapTypeId string | undefined
    The initial Map mapTypeId. Defaults to ROADMAP.初始Map mapTypeId。 默认为ROADMAP。

    onBoundsChanged (() => void) | undefined
    This event is fired when the viewport bounds have changed.视口边界更改时将触发此事件。

    onCenterChanged (() => void) | undefined
    This event is fired when the map center property changes.地图中心属性更改时,将触发此事件。

    onClick ((e: any) => void) | undefined
    This event is fired when the user clicks on the map. An ApiMouseEvent with properties for the clicked location is returned unless a place icon was clicked, in which case an IconMouseEvent with a placeid is returned. IconMouseEvent and ApiMouseEvent are identical, except that IconMouseEvent has the placeid field. The event can always be treated as an ApiMouseEvent when the placeid is not important. The click event is not fired if a marker or infowindow was clicked.用户单击地图时将触发此事件。 除非单击了位置图标,否则将返回一个具有单击位置属性的ApiMouseEvent,在这种情况下,将返回带有位置标识的IconMouseEvent。 IconMouseEvent和ApiMouseEvent是相同的,只是IconMouseEvent具有placeid字段。 当Placeid不重要时,可以始终将事件视为ApiMouseEvent。 如果单击了标记或信息窗口,则不会触发click事件。

    onDblClick ((e: any) => void) | undefined
    This event is fired when the user double-clicks on the map. Note that the click event will also fire, right before this one.用户双击地图时将触发此事件。 请注意,在此事件之前,click事件也会触发。

    onDrag (() => void) | undefined
    This event is repeatedly fired while the user drags the map.用户拖动地图时,反复触发此事件。

    onDragEnd (() => void) | undefined
    This event is fired when the user stops dragging the map.

    onDragStart (() => void) | undefined
    This event is fired when the user starts dragging the map.

    onHeadingChanged (() => void) | undefined
    This event is fired when the map heading property changes.地图标题属性更改时会触发此事件。

    onIdle (() => void) | undefined
    This event is fired when the map becomes idle after panning or zooming.当地图在平移或缩放后变得空闲时,将触发此事件。

    onLoad ((map: any) => void | Promise<void>) | undefined
    This callback is called when the component unmounts. It is called with the map instance.组件卸载时将调用此回调。 它与地图实例一起调用。

    onMapTypeIdChanged (() => void) | undefined
    This event is fired when the mapTypeId property changes.

    onMouseMove ((e: any) => void) | undefined
    This event is fired whenever the user's mouse moves over the map container.每当用户的鼠标移到地图容器上方时,就会触发此事件。

    onMouseOut ((e: any) => void) | undefined
    This event is fired when the user's mouse exits the map container.

    onMouseOver ((e: any) => void) | undefined
    This event is fired when the user's mouse enters the map container.

    onProjectionChanged (() => void) | undefined
    This event is fired when the projection has changed.更改投影后会触发此事件。

    onResize (() => void) | undefined
    This event is fired when the map size has changed.

    onRightClick ((e: any) => void) | undefined
    This event is fired when the DOM contextmenu event is fired on the map container.在地图容器上触发DOM上下文菜单事件时,将触发此事件。

    onTilesLoaded (() => void) | undefined
    This event is fired when the visible tiles have finished loading.可见的图块完成加载后会触发此事件。

    onTiltChanged (() => void) | undefined
    This event is fired when the map tilt property changes.地图倾斜属性更改时,将触发此事件。

    onUnmount ((map: any) => void | Promise<void>) | undefined
    This callback is called when the map instance has loaded. It is called with the map instance.地图实例加载后将调用此回调。 它与地图实例一起调用。

    onZoomChanged (() => void) | undefined
    This event is fired when the map zoom property changes.
    地图缩放属性更改时,将触发此事件。

    options any

    streetView any
    A StreetViewPanorama to display when the Street View pegman is dropped on the map. If no panorama is specified, a default StreetViewPanorama will be displayed in the map's div when the pegman is dropped.当街景街景小人放置在地图上时显示的StreetViewPanorama。 如果未指定全景图,则在放置街景小人时,默认的StreetViewPanorama将显示在地图的div中。

    tilt number | undefined
    Controls the automatic switching behavior for the angle of incidence of the map. The only allowed values are 0 and 45. The value 0 causes the map to always use a 0° overhead view regardless of the zoom level and viewport. The value 45 causes the tilt angle to automatically switch to 45 whenever 45° imagery is available for the current zoom level and viewport, and switch back to 0 whenever 45° imagery is not available (this is the default behavior). 45° imagery is only available for satellite and hybrid map types, within some locations, and at some zoom levels. Note: getTilt returns the current tilt angle, not the value specified by this option. Because getTilt and this option refer to different things, do not bind() the tilt property; doing so may yield unpredictable effects.控制地图的入射角的自动切换行为。 唯一允许的值为0和45。值0会使地图始终使用0°顶视图,而与缩放级别和视口无关。 值45使倾斜角度在当前缩放级别和视口可使用45°图像时自动切换为45,并在不可用45°图像时自动切换回0(这是默认行为)。 45°影像仅在某些位置和某些缩放级别下适用于卫星地图和混合地图类型。 注意:getTilt返回当前倾斜角度,而不是此选项指定的值。 因为getTilt和此选项引用的是不同的东西,所以不要bind()倾斜属性; 这样做可能会产生不可预测的影响。

    zoom number | undefined
    The initial Map zoom level. Required. Valid values: Integers between zero, and up to the supported maximum zoom level.初始地图缩放级别。 必填项。 有效值:介于0到最大支持的最大缩放级别之间的整数。

    封装LoadScript

    useLoadScript 返回结果之后执行renderMap

    import React from 'react';
    import { useLoadScript } from '@react-google-maps/api';
    import mapLoading from './mapLoading';
    
    const apiKey = "your api key";
    const googleMapsLibraries = ['drawing', 'visualization', 'places'];
    const version = 'quarterly';
    
    
    const LoadScript = (props: LoadScriptProps) => {
      const { googleMapsApiKey, language } = props;
      const { isLoaded } = useLoadScript({
        googleMapsApiKey: googleMapsApiKey || apiKey,
        language: language,
        version: version,
        libraries: googleMapsLibraries,
        preventGoogleFontsLoading: false,
      });
    
      const renderMap = () => {
        return <React.Fragment>
          { props.children }
        </React.Fragment>;
      };
    
      return isLoaded || window.google ? renderMap() : mapLoading();
    };
    
    interface LoadScriptProps {
      googleMapsApiKey?: string;
      language?: string;
      children?: React.ReactNode;
      onLoad?: (map: google.maps.Map) => void;
    }
    
    declare let window: ClientWindow;
    
    interface ClientWindow extends Window {
      google: any
    }
    
    export default LoadScript;
    

    封装GoogleMap

    onLoad(map)的参数就是此地图实例,load挂载之后再对实例进行设置

    import React from 'react';
    import { GoogleMap, GoogleMapProps } from '@react-google-maps/api';
    import uniqid from 'uniqid';
    
    const BaseMap = (props: BaseMapProps) => {
    
      const onLoad = map => {
        map.setOptions({
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          mapTypeControlOptions: {
            position: google.maps.ControlPosition.LEFT_BOTTOM
          },
          streetViewControlOptions: {
            position: google.maps.ControlPosition.RIGHT_BOTTOM
          },
          zoomControlOptions: {
            position: google.maps.ControlPosition.RIGHT_BOTTOM
          }
        });
        props.onLoad && props.onLoad(map);
      };
    
      const renderMap = () => {
        return <GoogleMap id={uniqid('map-')} { ...props } onLoad={onLoad} >
          {props.children}
        </GoogleMap >;
      };
    
      return renderMap();
    };
    
    export interface BaseMapProps extends GoogleMapProps {
      children?: React.ReactNode;
      googleMapsApiKey? : string;
      language?: string;
    }
    
    export default BaseMap;
    

    Marker & InfoWindow

    marker也有onLoad onLoad={(marker: google.maps.Marker) => {根据原生文档对marker进行操作}}
    InfoWindow:具体看文档
    参数anchor any
    Can be any MVCObject that exposes a LatLng position property and optionally a Point anchorPoint property for calculating the pixelOffset. The anchorPoint is the offset from the anchor's position to the tip of the InfoWindow.可以是任何公开LatLng位置属性的MVCObject,还可以是用于计算pixelOffset的Point anchorPoint属性(可选)。 anchorPoint是从锚点位置到InfoWindow尖端的偏移量。

    import React, { Component } from 'react';
    import { BaseMap, LoadScript, Marker } from '@components';
    // import { Marker } from '@react-google-maps/api';
    // import { GoogleMap } from '@react-google-maps/api';
    
    const mapProps = {
      mapContainerStyle: { height: `100%` },
      mapContainerClassName: 'map-box',
      zoom: 14,
      center: {
        lat: 41.8368,
        lng: -87.6792,
      },
      onLoad: (map: google.maps.Map) => {
        map.setOptions({
          // Remove Default UI
          disableDefaultUI: true,
        });
      }
    };
    
    const Info = () => {
      return <div className="map-info fs14">
        {`cccccccccccccc`}
      </div>;
    };
    
    export class Map extends Component {
      render() {
        const infoWindow = <Info />;
        return <div id="technicianMap" style={{ height: '70vh', width: '100%' }} >
          <LoadScript>
            <BaseMap {...mapProps} >
              <Marker
                infoWindowContent={infoWindow}
                onLoad={marker => {
                  console.log('marker: ', marker);
                }}
                position={{
                  lat: 41.8368,
                  lng: -87.6792,
                }}
              />
            </BaseMap>/>
          </LoadScript>
        </div>;
    
      }
    }
    
    export default Map;
    
    

    相关文章

      网友评论

          本文标题:@react-google-maps/api

          本文链接:https://www.haomeiwen.com/subject/wuajmctx.html