MicheleBertoli / react-gmaps

A Google Maps component for React.js

Home Page:http://react-gmaps.herokuapp.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

PolyLine for drawing lines between markers

copperstick6 opened this issue · comments

Hey!
I'm relatively new to this package, and I've been messing with it for the past couple of days. I'm just wondering if there is support for PolyLines (drawing and connecting markers) and if there are, please add a small code sample so that I can test it!
Thanks in advance.

I think I figured it out, but would like confirmation..
By utilizing the onMapCreated callback I can then utilize google.maps.Polyline to draw my polylines.
Closing issue since I found the solution =).

var polyline = new google.maps.Polyline({
I'm having an error here where google.maps is not defined. Any tips on solving this issue?

Hello @copperstick6
Are you running that code inside onMapCreated?
Can you please provide a non-working example?

yeah sure, here's my onMapCreated method:

  onMapCreated(map) {   
    map.setOptions({   
      disableDefaultUI: true   
    });   
    var coords = [];   
    for(var i = 0; i < this.props.list.length; i++){   
      coords.push({lat: this.props.list[i].lat, lng: this.props.list[i].long});   
    }  
    var polyline = new google.maps.Polyline({   
      path: coords,  
      geodesic: true,  
      strokeColor: '#FF0000',  
      strokeOpacity: 1.0,  
      strokeWeight: 2  
    });  
    polyline.setMap(map);  
  }

The error is: Line 192: 'google' is not defined no-undef

So the output of coords should look something like this:

var flightPlanCoordinates = [
          {lat: 37.772, lng: -122.214},
          {lat: 21.291, lng: -157.821},
          {lat: -18.142, lng: 178.431},
          {lat: -27.467, lng: 153.027}
        ];

So how I have it set up is the Map is a child component being rendered within two components. I've done some searching, but they all seem to point to putting the <script> with the google maps v3 js api into the html file header, but I have done that and it doesn't seem to be solving my problem.

Hey @MicheleBertoli I fixed the error. The error resided within using create-react-app which we were using to create our entire react application. The way to resolve the error is to add window.google.maps.Polyline when creating a google object. It would be nice if you could include a snippet to that effect within the Readme, since create-react-app is becoming more and more popular.

Git Issue resolved on the main create-react-app repo here

Hello @copperstick6 thanks for all the information.
I'm not sure if your problem is related to the tests (in that case the technique described in the issue you referenced is the right solution - it is also used in this repo), or the application in the browser.
In the second case, the problem might be different.
Thanks!

The problem is related to the application in the browser, I wrote my own react app using create-react-app and ran into this error where google was undefined and had to use window.google when creating PolyLines and Polygons. I'm not sure exactly what the root of the error is, or what's causing it, but it seems like when I create a react app manually (not using create-react-app) the problem does not exist.

This is interesting because google.maps should always exist when onMapCreated occurs since the map has been created.

It seems that with create-react-app you need to use window to use the google object

Got it, thanks!
It's a linting issue.

`import React, { Component } from "react";
import { Map, Marker, Popup, FeatureGroup,LayersControl,TileLayer } from "react-leaflet";
import ReactLeafletGoogleLayer from "react-leaflet-google-layer";
import { EditControl } from "react-leaflet-draw";
import L from "leaflet";
import "leaflet-routing-machine/dist/leaflet-routing-machine.css";
import "leaflet-routing-machine";

import { withLeaflet } from "react-leaflet"

import './centre.css'
import Routing from "./Routing";

import * as ELG from "esri-leaflet-geocoder";

const { BaseLayer } = LayersControl;

// import marker icons
delete L.Icon.Default.prototype._getIconUrl;

L.Icon.Default.mergeOptions({
iconRetinaUrl:
"https://unpkg.com/leaflet@1.4.0/dist/images/marker-icon-2x.png",
iconUrl: "https://unpkg.com/leaflet@1.4.0/dist/images/marker-icon.png",
shadowUrl: "https://unpkg.com/leaflet@1.4.0/dist/images/marker-shadow.png"
});

class Path extends Component {
constructor(props) {
super(props);
this.state = {
lat: 17.3850 ,
lng: 78.4867,
zoom: 13,
marker: [17.3850 ,78.4867]
};
}

componentDidMount() {
const map = this.leafletMap.leafletElement;
const searchControl = new ELG.Geosearch().addTo(map);
const results = new L.LayerGroup().addTo(map);
const Polyline = L.Polyline.Arc () ({
color: 'red',
vertices: 200
}).addTo(Map);

searchControl.on("results", function(data) {
  results.clearLayers();
  for (let i = data.results.length - 1; i >= 0; i--) {
    results.addLayer(L.marker(data.results[i].latlng));
  }
});
  
map.on("polyline", function(data) {
  
});

}

terrain = "TERRAIN";
key = "AIzaSyC0QH9aiCXuuRjJe4k5lzAM2bYl-MUhiPk";

removeEverything = e => {
console.log(e);
const { lat, lng } = e.layer._latlng;
this.setState({ marker: [lat, lng] });
const { edit } = this.refs;
var layerContainer = edit.leafletElement.options.edit.featureGroup;
const layers = layerContainer._layers;
const layer_ids = Object.keys(layers);
layer_ids.splice(0, 1);
layer_ids.forEach(id => {
const layer = layers[id];
layerContainer.removeLayer(layer);
});
};

setPos = () => {
this.setState({ marker: [17.3850, 78.4867] });
};

handleOnZoomed = e => {
this.setState({ zoom: e.target._zoom });
};

render() {
const position = [this.state.lat, this.state.lng];
const center = [17.3850, 78.4867];

return (
 <div>

    <pre>{JSON.stringify(this.state)}</pre>
    <button onClick={this.setPos}>remove</button>
    <Map
      center={this.state.marker}
      zoom={this.state.zoom}
      onzoomend={this.handleOnZoomed}
      ref={m => {
        this.leafletMap = m;
      }}
    >
       


      <Marker
        position={this.state.marker}
        defaultMarker={{ position: true }}
      >
      </Marker>
       
    

      <TileLayer
        attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <FeatureGroup>
        <EditControl
          ref="edit"
          position="topright"
          onCreated={this.removeEverything}
          CircleMarker ="true"
          removalMode ="true"
          pinningOption ="true"
          snappingOption = "true"
          draw={{
            rectangle: true,
            polygon:true,
            CircleMarker:true,
            removalMode:true,
            pinningOption:true,
            snappingOption:true

          }}
        />
      </FeatureGroup>
      {/* <ReactLeafletGoogleLayer
        googleMapsLoaderConf={{ KEY: this.key }}
        type={"satellite"}
      /> */}

    <div className="pointer" />
    </Map>
  
    </div>
);

}
}

export default Path`

polyline is not defined