GithubHelp home page GithubHelp logo

charmatzis / react-leaflet-google Goto Github PK

View Code? Open in Web Editor NEW
29.0 8.0 60.0 7.23 MB

GoogleMaps layer as React component for Leaflet | This repo is obsolete. Plz, use https://github.com/TA-Geoforce/react-leaflet-google

Home Page: https://github.com/TA-Geoforce/react-leaflet-google

License: MIT License

JavaScript 96.75% HTML 3.25%
leaflet react googlemaps-layer google-maps

react-leaflet-google's Introduction

react-leaflet-google npm version

GoogleMaps layer as React component for Leaflet build on top of React-Leaflet.

The google maps layer is using the plugin from Leaflet.GridLayer.GoogleMutant

Also it uses google-maps, a wrapper for asynchronously download Google Maps API in the browser.

Example

supported versions

  • "react-leaflet": "^1.9.1"
  • "leaflet": "^1.3.0""
  • "react": "^15.0.0 || ^16.0.0"

Getting started

import { Map, TileLayer, LayersControl } from 'react-leaflet'
import {GoogleLayer} from '../src'
const { BaseLayer } = LayersControl;
const key = 'Your Key goes here';
const terrain = 'TERRAIN';
const road = 'ROADMAP';


....

  <BaseLayer checked name='Google Maps Roads'>
     <GoogleLayer googlekey={key}  maptype={road}/>
  </BaseLayer>
  <BaseLayer  name='Google Maps Terrain'>
     <GoogleLayer googlekey={key}  maptype={terrain} />
  </BaseLayer>


For more details on how to use this plugin check the example.

react-leaflet-google's People

Contributors

charmatzis avatar cmilfont avatar danieldunderfelt avatar getaasciesh avatar ivan-hilckov avatar ivorbosloper avatar laurianek avatar pyxarez avatar rajadain avatar svanachterbergh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-leaflet-google's Issues

Make googlekey optional

If you just want to use the google maps layer without any other functionality it works fine without an API key but react-leaflet-google shows an error because the googlekey is marked as required.

Unable to use in client side rendering

Hi,
have you used this in single page app what renders the map on client side?

On the second time when I render the map (for instance visiting in other page and coming back), I get following error and the map tiles don't show up at all:
screen shot 2016-08-21 at 11 34 51

Have to refresh the page to get it work again.

I manage to get it working without errors properly by doing following changes, but I'm not familiar enough with the codebase to understand is there some other concequences with these changes:

        GoogleMapsLoader.load(function (_google) {
            google = _google;
            console.log('I just loaded google maps api');
            self._ready = true; // <---- ADDED THIS!
            self._initMapObject();
            self._update();

            //this._ready = google.maps.Map !== undefined;
            //if (!this._ready) L.Google.asyncWait.push(this);
        });
    _initMapObject: function () {
        if (!this._ready || !this._container) return; // <--- ADDED _container check!

        this._google_center = new google.maps.LatLng(0, 0);
        var map = new google.maps.Map(this._container, {
            center: this._google_center,

         // CODE CONTINUES....

Any help?

Google Hybrid BaseLayer does not display street or place names

Thanks for your hard work. Everything works great, but the hybrid view (satellite+place/street names) only shows satellite imagery-no names.

I did notice, loading it on a bad connection, that the layer with the names shows up briefly and then is buried, which makes me wonder if it's a z-index issue.

My component:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';
import { Map, TileLayer, LayersControl, MapControl } from 'react-leaflet';
import { GoogleLayer } from './GoogleLayer';
import { geolocated } from 'react-geolocated';
import 'leaflet-geocoder-mapzen';
import SearchBox from './searchBox';
import Control from 'react-leaflet-control';
import { centroid } from '@turf/turf';
import PlotMarker from './plotMarker';

const { BaseLayer } = LayersControl;
const key = 'MYKEY';
const hybrid = 'HYBRID';
const terrain = 'TERRAIN';
const road = 'ROADMAP';
const satellite = 'SATELLITE';

const centerLat = props => {
	if (
		props.isGeolocationAvailable &&
		props.isGeolocationEnabled &&
		props.coords
	) {
		return props.coords.latitude;
	}
	return 32.11;
};

const centerLong = props => {
	if (
		props.isGeolocationAvailable &&
		props.isGeolocationEnabled &&
		props.coords
	) {
		return props.coords.longitude;
	}
	return 34.963;
};

const mapCenterPoint = props => {
	if (props.plots && props.selectedPlot) {
		let ourPlot = props.plots.filter(
			plot => plot._id === props.selectedPlot
		)[0];
		try {
			let center = centroid(ourPlot.feature).geometry.coordinates.reverse();
			return { center: center, zoom: 16 };
		} catch (e) {
			console.log(e);
		}
	}
	return { center: [centerLat(props), centerLong(props)], zoom: 8 };
};

export class PlotMap extends Component {
	markers = props => {
		if (props.plots) {
			return (
				<div>
					{(props.filteredPlots || props.plots).map(
						plot =>
							plot.feature &&
							plot._id && (
								<PlotMarker
									key={plot._id}
									id={plot._id}
									name={plot.name}
									geoJSON={plot.feature}
								/>
							)
					)}
				</div>
			);
		}
	};

	render() {
		return (
			<div
				className="col-sm-8 m-auto p-0 flex-column float-right"
				style={{ height: `85vh` }}>
				<Map
					center={mapCenterPoint(this.props).center}
					zoom={mapCenterPoint(this.props).zoom}
					zoomControl={true}
					onZoomend={e => {
						this.props.setZoomLevel(e.target.getZoom());
					}}
					onMoveEnd={e => {
						this.props.setMapCenter(e.target.getCenter());
					}}>
					<LayersControl position="topright">
						<BaseLayer name="Google Maps Roads">
							<GoogleLayer googlekey={key} maptype={road} />
						</BaseLayer>
						<BaseLayer name="Google Maps Terrain">
							<GoogleLayer googlekey={key} maptype={terrain} />
						</BaseLayer>
						<BaseLayer checked name="Google Maps Hybrid">
							<GoogleLayer
								googlekey={key}
								maptype={hybrid}
								libraries={['geometry', 'places']}
							/>
						</BaseLayer>
					</LayersControl>
					<SearchBox postion="bottomright" />
					{this.markers(this.props)}
				</Map>
			</div>
		);
	}
}

props.leaflet is undefined

I'm trying to display the map from google with leaflet 1.3.4 and react-leaflet 2.1.0.
I've this code

<Map                                                                                                                                                                                                         
  className={this.props.className}                                                                                                                                                                           
  center={this.props.center}                                                                                                                                                                                 
  zoom={13}                                                                                                                                                                                                  
>                                                                                                                                                            
  <GoogleLayer                                                                                                                                                                                                 
    googlekey={this.props.googleMapToken}                                                                                                                                                                      
    maptype="TERRAIN"                                                                                                                                                                                          
  />
</Map>

But I get this error

uncaught at _callee Error: props.leaflet is undefined
getOptions@http://localhost:3000/static/js/bundle.js:77382:5
createLeafletElement@http://localhost:3000/static/js/bundle.js:77363:67
MapLayer@http://localhost:3000/static/js/bundle.js:78404:28
GridLayer@http://localhost:3000/static/js/bundle.js:77357:12
GoogleLayer@http://localhost:3000/static/js/bundle.js:75274:47
constructClassInstance@http://localhost:3000/static/js/bundle.js:62331:18
updateClassComponent@http://localhost:3000/static/js/bundle.js:64053:7
beginWork@http://localhost:3000/static/js/bundle.js:64652:16
performUnitOfWork@http://localhost:3000/static/js/bundle.js:66978:12
workLoop@http://localhost:3000/static/js/bundle.js:67016:24
renderRoot@http://localhost:3000/static/js/bundle.js:67095:7
performWorkOnRoot@http://localhost:3000/static/js/bundle.js:67949:7
performWork@http://localhost:3000/static/js/bundle.js:67857:7
performSyncWork@http://localhost:3000/static/js/bundle.js:67829:3
requestWork@http://localhost:3000/static/js/bundle.js:67717:5

Do you have any idea why?

edge tiles don't load with zoom snap < 1

When react-leaflet's zoomSnap is, say, 0.5, Google tile layers often (presumably at half-level zooms) do not cover the entire view (see screenshot). For now, my solution is, of course, to use zoomSnap=1, but this should probably be fixed.

image

Uncaught TypeError: Cannot read property 'offsetWidth' of undefined

I added react-leaflet-google to my project and it seems to work fine but it always shows the following error in the console:
screen shot 2016-09-08 at 09 19 02

Here's my code:

import React from 'react';
import { Map, TileLayer, LayersControl } from 'react-leaflet';
import { GoogleLayer } from 'react-leaflet-google';
import 'leaflet/dist/leaflet.css';
import '../css/map.css';

const { BaseLayer } = LayersControl;

export default React.createClass({
  render() {
    return (
      <Map className="map" bounds={this.props.bounds} >
        <LayersControl position="topright">
          <BaseLayer name="OpenStreetMap">
            <TileLayer
              url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            />
          </BaseLayer>
          <BaseLayer checked name="Google Maps Terrain">
            <GoogleLayer type="TERRAIN" />
          </BaseLayer>
          <BaseLayer name="Google Maps Hybrid">
            <GoogleLayer type="HYBRID" />
          </BaseLayer>
          <BaseLayer name="Google Maps Roadmap">
            <GoogleLayer type="ROADMAP" />
          </BaseLayer>
        </LayersControl>
        {this.props.children}
      </Map>
    );
  },
});

I'm using react-leaflet 0.12.1 and react-leaflet-google 1.1.0.
Feel free to ask if you need more information about my issue.

version 3.32 being listed as Retired

3.32 is producing a console warning as being retired. Unfortunately this also triggers an error warning for my codebase as there's an exception thrown (Sentry). Do you need a PR to update the hardcoded version?

react-leaflet-google is still working?

Hi, I'm trying to make working react-leaflet-google (4.0.0) with a project using react-leaflet (2.2.1). It's impossible to render anything. Is this package still working or maybe it's my way of using it?
Many thanks!

Zoom issue when passing styles to GoogleLayers

Greetings,

I have the following working code which works fine:

import { Map, ZoomControl } from 'react-leaflet'
import { GoogleLayer} from 'react-leaflet-google';

export class MapContainer extends React.Component {
  (...)
  render() {
    return (
      <Map id="map" ref={this.mapRef} zoomControl={false}>
        <ZoomControl position="bottomright" />
        <GoogleLayer
          googlekey={my_key}
          maptype='ROADMAP'
        />
      </Map>
    );
  }
}

However, when I try to create a GoogleLayer with only labels like this:

import { Map, ZoomControl } from 'react-leaflet'
import { GoogleLayer} from 'react-leaflet-google';

export class MapContainer extends React.Component {
  (...)
  render() {
    return (
      <Map id="map" ref={this.mapRef} zoomControl={false}>
        <ZoomControl position="bottomright" />
        <GoogleLayer
          googlekey={my_key}
          maptype='ROADMAP'
          styles ={[
            {elementType: 'all', stylers: [{visibility: 'off'}]},
            {elementType: 'labels', stylers: [{visibility: 'on'}]},
          ]}
        />
      </Map>
    );
  }
}

I run into a problem with the zoom. After zooming out, and then zooming in again, I end up with a mix of labels from the previous zoom and the new one:

screenshot 2018-11-05 15 01 50

This clears out, after I do one or two more zoom ins

I'm using
[email protected]
[email protected]
[email protected]

Anyone experienced this before?

Thank you!

EDIT:

This is reproducible event if I try disabling only landscape features:

styles ={[ 
     {featureType:"landscape", stylers: [{visibility: 'off'}]},
]}

screenshot 2018-11-05 15 54 19

Avoid loading google maps twice, make GoogleMapsLoader webpack-external

Hi,

I'm trying to combine react-leaflet-google with another component (react-geosuggest) that uses the google maps API and I just can't avoid loading the API twice. This results in the google-maps error

You have included the Google Maps API multiple times on this page. This may cause unexpected errors

The other component suggests to include the google javascript directly in the page, but the GoogleMapsLoader used in this project always loads its own version. I've changed my setup to use GoogleMapsLoader in the whole project (using webpack), but a second version of the GoogleMapsLoader code is included in my bundle, with again a private google variable, still loading the google api twice. I believe that this is caused by webpack.config.js in this project, which does not mention 'google-maps'/GoogleMapsLoader as an externals dependency, and therefore creating a dist-bundle with a private version of GoogleMapsLoader.

I've just started using webpack, am I right in this analysis?

Google Maps JavaScript API warning: RetiredVersion

Google Maps JavaScript API warning: RetiredVersion

import React from 'react';
import { Consumer } from './../base/Provider';
import { Map } from 'react-leaflet';
import { GoogleLayer } from 'react-leaflet-google';

/**
 * Google Map area component
 */
class MapArea extends React.Component {
	state = {
		lat: 42.09618442380296,
		lng: -71.5045166015625,
		zoom: 13,
	};

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

		// noinspection RequiredAttributes
		return (
			<Map center={position} zoom={this.state.zoom} zoomControl={true}>
				<GoogleLayer  googlekey={'@googleApiKey'} maptype="road" />
			</Map>
		);
	}
}

MapArea.contextType = Consumer;

export default MapArea;

Above code produces following warning:

Google Maps JavaScript API warning: RetiredVersion https://developers.google.com/maps/documentation/javascript/error-messages#retired-version
mw.m                	util.js:221
(anonymous function)	js:122
Async call from Promise.then
(anonymous function)	js:122
Async call from setTimeout
Bh                  	js:122
google.maps.Load    	js:21
(anonymous function)	js:211
(anonymous function)	js:211

When routing away from route where map is rendered, error "TypeError: Cannot read property 'bottomright' of undefined"

HOW TO REPRODUCE

(example code below)

  • Put the Map with Google Layer in some route (I'm using React-router v3 here with react-redux-router).
  • Put one Marker with a Popup inside with a link which dispatches a routing action
  • Click on the link > check console

MAP

<Map {...props}>
<GoogleLayer
      googlekey={key}
      maptype={mapType}
      styles={styles}
 />
</Map>

Marker

<Marker>
     <Popup>
         <a onClick={goTo} />
    </Popup>
</Marker>

goTo() {
    dispatch(push(<anything>);)
}

ERROR:

reactBoilerplateDeps.dll.js:205346 Uncaught (in promise) TypeError: Cannot read property 'bottomright' of undefined
    at NewClass.onRemove (reactBoilerplateDeps.dll.js:205346)
    at NewClass.removeLayer (reactBoilerplateDeps.dll.js:95784)
    at NewClass.removeFrom (reactBoilerplateDeps.dll.js:95669)
    at NewClass.remove (reactBoilerplateDeps.dll.js:95662)
    at NewClass.remove (reactBoilerplateDeps.dll.js:92953)
    at Map.componentWillUnmount (reactBoilerplateDeps.dll.js:210619)
    at reactBoilerplateDeps.dll.js:185672
    at measureLifeCyclePerf (reactBoilerplateDeps.dll.js:185338)
    at ReactCompositeComponentWrapper.unmountComponent (reactBoilerplateDeps.dll.js:185671)
    at Object.unmountComponent (reactBoilerplateDeps.dll.js:192107)

Gmaps tiles have an offset

Hi,
thanks a lot for the gmaps wrapper library. However, in my use case (map in a dialog) the google map tiles have an offset. I will attach two screenshots to make my point clearer. This leads to different coordinates on the onClick function. I would very glad if you could point out my mistake or tell me why this happening.
The osm map is render right and the onClick coordinates are correct.
screenshot from 2017-03-01 12 51 28

screenshot from 2017-03-01 12 51 56

Uncaught TypeError: Cannot read property 'getAttribute' of undefined

Hi. I'm using the latest version of react-leaflet-google and when rendering the tile of the google maps, an error will occur on line leaflet-src.js:11297. See below.

Uncaught TypeError: Cannot read property 'getAttribute' of undefined
    at NewClass._tileReady (leaflet-src.js:11297)
    at NewClass.<anonymous> (react-leaflet-google.js:1657)
    at NewClass._onMutatedImage (react-leaflet-google.js:1603)
    at NodeList.forEach (<anonymous>)
    at NewClass._onMutations (react-leaflet-google.js:1545)

The specific version the libraries dependencies I'm using are:

[email protected]
[email protected]
google-maps@^3.3.0
react@^16.4.1
react-leaflet-google@^3.3.1
react-dom@^16.4.1

screenshot from 2018-07-30 14-39-11_2

Support version v3 in a separate branch?

Hi,

I am currious if you would be willing to support v3 in a separate branch, we have run into retired version warning for google maps, and i am willing to send a patch for new version of old version 3.3.1 if you are interested to support it. In that case we would need a new branch for v3 which is based on version 3.3.1, and i would create a PR for that branch, publishing that version should be possible by using npm publish --tag old-version

Resizing of parent container not handled

Hi, thanks for the wrapper! I have used it till now nearly without any issues. However, after now I stumbled across a resizing problem.

If I resize the map container it appears that the google tile layer is not resized and grey areas are visible. (see right end)
error

If I do the resizing with OSM everything works well.
working

FYI, I am calling the invalidateSize method of the map after the resize event.

setTimeout(function () {
            if (this.map && this.map.leafletElement) { 
              console.log("updateMapSize started");
              this.map.leafletElement.invalidateSize(true); 
            }
          }.bind(this), 1000);

Also worth pointing out, is that this only happens in the roadmap mode, with the satellite mode it works perfect.

TypeError: Cannot read property 'setCenter' of undefined

Hi,

i have a blinking problem on test server using this.map.fitBounds(boundCoords) in componentDidUpdate:

TypeError: Cannot read property 'setCenter' of undefined
    at n._handleZoomAnim (react-leaflet-google.js:1635)
    at n.fire (leaflet-src.js:593)
    at n._moveEnd (leaflet-src.js:4193)
    at n._resetView (leaflet-src.js:4137)
    at n.setView (leaflet-src.js:3191)
    at n.fitBounds (leaflet-src.js:3280)
    at t.value (Map.js:211)

And in the source code file dist/react-leaflet-google.js I see that there isn't check on undefined value of this._mutant in _handleZoomAnim like in other methods:

_handleZoomAnim: function _handleZoomAnim() {
	    var center = this._map.getCenter();
	    var _center = new google.maps.LatLng(center.lat, center.lng);
	    this._mutant.setCenter(_center);
	    this._mutant.setZoom(Math.round(this._map.getZoom()));
	  },

In _resize method:

_resize: function _resize() {
	    var size = this._map.getSize();
	    if (this._mutantContainer.style.width === size.x && this._mutantContainer.style.height === size.y) return;
	    this.setElementSize(this._mutantContainer, size);
	    *if (!this._mutant) return;*
	    google.maps.event.trigger(this._mutant, "resize");
	  },

Should it be?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.