如何使用 react-google-maps 库创建折线

IT技术 google-maps reactjs google-maps-api-3
2021-05-19 02:00:00

我正在尝试使用 react-google-maps 库在 4 个 GPS 坐标之间绘制折线。地图上没有渲染

import React from 'react';
import { withGoogleMap, GoogleMap, Marker, InfoWindow,Polyline } from 'react-google-maps';


class googleMapComponent extends React.Component {

//高阶组件​​:withGoogleMap 用作函数调用。此功能返回另一个组件定义,该定义稍后安装在渲染中

 // maintain a refernce to a map inside the component, so that
    constructor(){
        super()
        this.state ={
            map:null
        }
    }

    mapMoved(){
        console.log('mapMoved: ' + JSON.stringify(this.state.map.getCenter()))
    }

    mapLoaded(map){
        //console.log('mapLoaded: ' + JSON.stringify(map.getCenter()))
        if(this.state.map !==null)
            return

        this.setState({
            map:map
        })
    }

    zoomchanged(){
        console.log('mapZoomed: ' + JSON.stringify(this.state.map.getZoom()))
    }
    handleMarkerClick(targetMarker) {
        this.setState({
            markers: this.state.markers.map(marker => {
                if (marker === targetMarker) {
                    return {
                        ...marker,
                        showInfo: true,
                    };
                }
                return marker;
            }),
        });
    }

    handleMarkerClose(targetMarker) {
        this.setState({
            markers: this.state.markers.map(marker => {
                if (marker === targetMarker) {
                    return {
                        ...marker,
                        showInfo: false,
                    };
                }
                return marker;
            }),
        });
    }

    render() {

        const markers= [
            {
                position: new google.maps.LatLng(36.05298766, -112.0837566),
                showInfo: false,
                infoContent: false,
            },
            {
                position: new google.maps.LatLng(36.21698848, -112.0567275),
                showInfo: false,
                infoContent: false,
            },
        ]
        const lineCoordinates= [
        {coordinate:  new google.maps.LatLng(36.05298766, -112.0837566)},
        {coordinate:  new google.maps.LatLng(36.0529832169413, -112.083731889724)},
        {coordinate:  new google.maps.LatLng(36.0529811214655, -112.083720741793)},
        {coordinate:  new google.maps.LatLng(36.0529811214655, -112.083720741793)},
    ]

        return (
            <GoogleMap
                ref={this.mapLoaded.bind(this)}
                onDragEnd={this.mapMoved.bind(this)}
                onZoomChanged={this.zoomchanged.bind(this)}
                defaultZoom={this.props.zoom}
                defaultCenter={this.props.center}
            >
                {markers.map((marker, index) => (
                    <Marker
                        position={marker.position}
                        title="click on it Sir..!!"
                        defaultPosition={this.props.center}
                        style={{height: '2xpx', width: '2px'}}
                    />
                ))}

                {lineCoordinates.map((polyline,index)=>(
                <Polyline
                    defaultPosition={this.props.center}
                    path= {polyline.coordinate}
                    geodesic= {true}
                    strokeColor= {#FF0000}
                    strokeOpacity= {1.0}
                    strokeWeight= {2}
                />

            </GoogleMap>

        )
    }
}
export default withGoogleMap(googleMapComponent);

任何关于它的建议都会有所帮助。如果库不支持此功能。我也可以切换图书馆。

3个回答

是的。例子:

render() {
    const pathCoordinates = [
        { lat: 36.05298765935, lng: -112.083756616339 },
        { lat: 36.2169884797185, lng: -112.056727493181 }
    ];
    return (
        <GoogleMap
            defaultZoom={this.props.zoom}
            defaultCenter={this.props.center}
        >
            {/*for creating path with the updated coordinates*/}
            <Polyline
                path={pathCoordinates}
                geodesic={true}
                options={{
                    strokeColor: "#ff2527",
                    strokeOpacity: 0.75,
                    strokeWeight: 2,
                    icons: [
                        {
                            icon: lineSymbol,
                            offset: "0",
                            repeat: "20px"
                        }
                    ]
                }}
            />
        </GoogleMap>
    );
}

一个更简单的例子来显示只绘制一条折线:

<GoogleMap defaultZoom={7} defaultCenter={{ lat: -34.897, lng: 151.144 }}>
    <Polyline path={[{ lat: -34.397, lng: 150.644 }, { lat: -35.397, lng: 151.644 }]}/>
</GoogleMap>

任何不清楚正确导入和设置(使用重构)的人的整个片段

import React from "react";
import ReactDOM from "react-dom";
import { compose, withProps } from "recompose";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
  Polyline
} from "react-google-maps";

const MyMapComponent = compose(
  withProps({
    googleMapURL:
      "https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />
  }),
  withScriptjs,
  withGoogleMap
)(props => (
  <GoogleMap defaultZoom={7} defaultCenter={{ lat: -34.897, lng: 151.144 }}>
    <Polyline path={[{ lat: -34.397, lng: 150.644 }, { lat: -35.397, lng: 151.644 }]}/>
  </GoogleMap>
));

ReactDOM.render(<MyMapComponent />, document.getElementById("root"));

与上面相同的示例,没有 recompose

import React from "react";
import ReactDOM from "react-dom";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Polyline
} from "react-google-maps";

const InternalMap = props => (
  <GoogleMap defaultZoom={7} defaultCenter={{ lat: -34.897, lng: 151.144 }}>
    <Polyline
      path={[{ lat: -34.397, lng: 150.644 }, { lat: -35.397, lng: 151.644 }]}
    />
  </GoogleMap>
);

const MapHoc = withScriptjs(withGoogleMap(InternalMap));

const MyMapComponent = props => (
  <MapHoc
    googleMapURL="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&v=3.exp&libraries=geometry,drawing,places"
    loadingElement={<div style={{ height: `100%` }} />}
    containerElement={<div style={{ height: `400px` }} />}
    mapElement={<div style={{ height: `100%` }} />}
  />
);

ReactDOM.render(
  <MyMapComponent />,
  document.getElementById("root")
);

当您运行映射函数时,您是否为每组坐标创建了一条新的折线?查看Google Maps 文档,折线将一组对象作为路径参数。google-maps-react 只是该 API 的包装器,因此您应该能够通过传入对象数组作为路径来创建折线。目前,您正在尝试根据微小的坐标片段生成一堆折线对象。