Anu
Anu

Reputation: 3430

How to create Polyline using react-google-maps library

I am trying to plot Polyline between 4 GPS coordinates using react-google-maps library. Nothing is rendering on the map

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


class googleMapComponent extends React.Component {

//Higher order components: withGoogleMap is employed as a function call. This fucntion returns another component defination which is later mounted in render

 // 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);

Any suggestion on it will be helpful. If the library does not support this functionality. I can swtich the library too.

Upvotes: 3

Views: 20978

Answers (3)

Jayant Bhawal
Jayant Bhawal

Reputation: 2204

A simpler example to show just one polyline being drawn:

<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>

Entire snippet for anyone unclear about the correct imports and setup (with recompose):

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"));

Same example as above, without 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")
);

Upvotes: 3

Anu
Anu

Reputation: 3430

Yes. Example:

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>
    );
}

Upvotes: 11

ricky
ricky

Reputation: 242

When you run the mapping function, are you creating a new polyline for each set of coordinates? Looking at the Google Maps docs, the polyline takes an array of objects as a path argument. google-maps-react is just a wrapper around that API, so you should be able to create your polyline just by passing in the array of objects as the path. Currently, you're trying to generate a bunch of polyline objects based on tiny coordinate fragments.

Upvotes: 3

Related Questions