tomchentw / react-google-maps Goto Github PK
View Code? Open in Web Editor NEWReact.js Google Maps integration component
Home Page: https://tomchentw.github.io/react-google-maps/
License: MIT License
React.js Google Maps integration component
Home Page: https://tomchentw.github.io/react-google-maps/
License: MIT License
Since Map is a global object in ES6, redefining it to a React class may have some side effects.
I'd prefer to split out logics to two functions:
SimpleChildComponent#_createInstance
SimpleChildComponent#_updateInstance
So that subclasses are free and clear to modify
Cool library. I suggest an enhancement to get around a know google maps memory leak (http://stackoverflow.com/questions/21142483/google-maps-js-v3-detached-dom-tree-memory-leak).
I think the best fix would be to see if there are any available google maps objects for reuse. If not, create one. On unmount return the google map object to the pool after the call to _set_map(null)
.
โ react-google-maps git:(master) sudo npm run dev_install
> [email protected] dev_install /Users/harshabhat/Documents/ReactJSTutorials/projects/react-google-maps
> npm install && npm dedupe && bower install
-
> [email protected] install /Users/harshabhat/Documents/ReactJSTutorials/projects/react-google-maps/node_modules/sass-loader/node_modules/node-sass
> node scripts/install.js
Binary downloaded and installed at /Users/harshabhat/Documents/ReactJSTutorials/projects/react-google-maps/node_modules/sass-loader/node_modules/node-sass/vendor/darwin-x64/binding.node
> [email protected] postinstall /Users/harshabhat/Documents/ReactJSTutorials/projects/react-google-maps/node_modules/sass-loader/node_modules/node-sass
> node scripts/build.js
`darwin-x64` exists; testing
Binary is fine; exiting
npm ERR! peerinvalid The package react does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants react@^0.13.2
npm ERR! peerinvalid Peer [email protected] wants react@^0.13.0
npm ERR! System Darwin 14.1.0
npm ERR! command "/Users/harshabhat/.nvm/v0.10.38/bin/node" "/Users/harshabhat/.nvm/v0.10.38/bin/npm" "install"
npm ERR! cwd /Users/harshabhat/Documents/ReactJSTutorials/projects/react-google-maps
npm ERR! node -v v0.10.38
npm ERR! npm -v 1.4.28
npm ERR! code EPEERINVALID
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /Users/harshabhat/Documents/ReactJSTutorials/projects/react-google-maps/npm-debug.log
npm ERR! not ok code 0
npm ERR! [email protected] dev_install: `npm install && npm dedupe && bower install`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] dev_install script.
npm ERR! This is most likely a problem with the react-google-maps package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! npm install && npm dedupe && bower install
npm ERR! You can get their info via:
npm ERR! npm owner ls react-google-maps
npm ERR! There is likely additional logging output above.
npm ERR! System Darwin 14.1.0
npm ERR! command "/Users/harshabhat/.nvm/v0.10.38/bin/node" "/Users/harshabhat/.nvm/v0.10.38/bin/npm" "run" "dev_install"
npm ERR! cwd /Users/harshabhat/Documents/ReactJSTutorials/projects/react-google-maps
npm ERR! node -v v0.10.38
npm ERR! npm -v 1.4.28
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /Users/harshabhat/Documents/ReactJSTutorials/projects/react-google-maps/npm-debug.log
npm ERR! not ok code 0
Hello,
How can I get instance of google map in react?
I need work with triggers
Thanks.
One can declare a Google Maps component with the following syntax:
import {GoogleMaps, Marker, Polygon} from "react-google-maps";
class MyFancyMapsContainer extends React.Component {
render () {
const {props, state} = this;
return (
<GoogleMaps style={{height:"100%"}} center={props.center}>
<Marker lat=0 lng=0 />
< Polygon paths={props.paths} />
</GoogleMaps>
);
}
}
import {GoogleMaps, Marker, Polygon} from "react-google-maps";
class MyFancyMapContainer extends React.Component {
render () {
const {props, state} = this;
return (
<div className="row">
<div className="col-xs-6">
<GoogleMaps style={{height:"100%"}} center={props.centerLeft}>
<Marker lat=0 lng=0 />
< Polygon paths={props.pathsLeft} />
</GoogleMaps>
</div>
<div className="col-xs-6">
<GoogleMaps style={{height:"100%"}} center={props.centerRight}>
<Marker lat=0 lng=0 />
< Polygon paths={props.pathsRight} />
</GoogleMaps>
</div>
</div>
);
}
}
As bower is not a dependency of react-google-maps
the installation fails if you donโt have bower installed globally.
I think the best solution would be to remove bower install
from the postinstall
hook and publish only the built bundle to the npm registry.
Hi,
how to create custom button like control button ?
Thanks for any advice.
The GoogleMaps
wrapper component breaks the React lifecycle because it does not re-render the VirtualContainer until after it is done updating everything.
This means trying to get an updated value from a newly-changed Marker
, for example, is not possible in any parent component's componentDidUpdate
method, because the children of the VirtualContainer are not yet re-rendered.
This is a regression from the previous mixin/context methodology, and leads to very confusing and difficult to debug errors.
Perhaps one solution would be to re-render VirtualContainer on componentWillUpdate
instead.
Support for the Google Maps Places Autocomplete and SearchBox widgets would be great, as it would provide an easy way to search for locations on the map (a common use case).
In order to make it work, I think we would have to do the following:
google.maps.places.SearchBox
and google.maps.places.Autocomplete
classes with SimpleChildComponent
var searchBox = new google.maps.places.SearchBox(inputNode)
), which we could construct on the fly before mount and remove on unmount
React.findDOMNode
or dangerouslySetInnerHtml
?) but that would be trickierplaces_changed
event on the SearchBox
and Autocomplete
components as onPlacesChanged
setBounds(LatLngBounds)
method of SearchBox
/Autocomplete
via the props
This should allow for something like:
// Updates the bounds of the map to the current search results
// and biases the search results to the current map location
class PlacesMap extends React.Component {
getInitialState() {
return { bounds: new google.maps.LatLngBounds() };
}
_set_bounds_(bounds) {
this.setState({ bounds });
}
_places_changed_() {
let places = this.refs.search.getPlaces();
if (places.length == 0) return;
let bounds = new google.maps.LatLngBounds();
for (let i = 0; i < places.length; i++) {
bounds.extend(places[i].geometry.location);
}
this._set_bounds_(bounds);
}
render () {
const {props, state} = this,
{googleMapsApi, ...otherProps} = props;
return (
<GoogleMaps containerProps={{
...otherProps,
style: {
height: "100%",
},
}}
onBoundsChanged={this._set_bounds_}
ref="map"
googleMapsApi={google.maps}
zoom={8}
center={{lat: -34.397, lng: 150.644}}>
<SearchBox ref="search" bounds={state.bounds} onPlacesChanged={this._places_changed_}>
</GoogleMaps>
);
}
}
Thoughts?
https://github.com/tomchentw/react-google-maps/blob/master/src/Rectangle.js#L11 _RectangleCreator
no longer exists
It will be nice to have a simple example usage in the docs for the Map and Marker. One should not have to dig through the example codes to figure out the basics. In my case I need a draggable marker
Hi, I see these event_names:
const BASIC_EVENT_NAMES = (
"click dblclick drag dragend dragstart mousedown mousemove mouseout mouseover mouseup rightclick"
);
How about tablet support with touch events? Are they supported somehow?
@tomchentw
Is there any support for the Google Maps drawing API via this project?
This is crucial for me, so if it's not built in, is there a way I can get a reference to the underlying Google Maps map
object so I can point a DrawingManager
I instantiate at it?
I have some overlay views with react content on map. Content have onClick handlers.
Also I have onClick handler on map.
When I click on overlay view content map receive click too.
As I noticed, map receive click event first. And second is overlay view.
And is is the problem.
Could you provide some more documentation on how to use these <GoogleMaps />
helper methods?
Hi, I'm having the following error : Uncaught TypeError: Cannot read property 'firstChild' of undefined
.
The error is triggered by this line in the componentDidMount
hook of GoogleMap
:
const domEl = findDOMNode(this);
source
Could this be caused by the fact i'm using react 0.14.0-beta1 ? Or do you have any idea what can cause this ?
Many thanks
Great work by @wuct! Go ahead and create a PR!!
thanks for this component, saving me time for sure! one thing i'm trying to do at the moment is zoom in on the bounds of the markers I have loaded into the map.
var venues = this.props.venues;
var latlngList = [];
var bounds = new google.maps.LatLngBounds();
var l = venues.length;
var lL;
var coordinate;
while (l--) {
coordinate = venues[l].coordinate;
latlngList.push(new google.maps.LatLng (coordinate[1],coordinate[0]));
}
lL = latlngList.length;
while (lL--) {
bounds.extend(latlngList[lL]);
}
this.refs.map.fitBounds(bounds);
I have a ref on the component, and it's calling the method in componentDidMount, but it's not zooming in to fit the bounds.
is there something else I have to do to get the map to react to what i'm doing?
I have this same code working in a non-reactjs based mapping app.
Hey,
If I'm using drawing manager, and make a polygon, how would I go around getting the polygon points?
This is actually a question. I want to highlight polylines on hover event.
I am doing that in in the following fashion:
That works, but leads to blinking of the map controls - apparently, they are rerendered. What I expect to have - to mimic native Google Maps solution, when you bind polyline.setOptions to the mouseover event, which doesn't lead to rerendering of the controls.
What's the best way to achieve that with react-google-maps?
Thanks!
Is it possible that you show us the changes that need to be made (or if it is just one file upload it) so that we can compile the solution in a Windows machine? (that has npm and node of course).
Thank you.
It seems that the content in the InfoWindow has to be a String.
However it would be nice to allow more complex UI's here, like a React component as the content.
Great library! Just one hiccup I've noticed so far:
When including a child in <GoogleMap>
that could include an object (such as a Marker
) the magic mapHolderRef
property doesn't get attached to the underlying Marker
object.
For example creating a structure something like:
<GoogleMap />
<MyMarkerHolder />
<Marker />
Will result in none of the <Markers />
having the necessary property set. The current workaround is to add a property in MyMarketHolder
that establishes the link:
<GoogleMap />
<MyMarketHolder mapHolderRef={this.props.mapHolderRef} />
<Marker />
The relevant code in creators/GoogleMapHolder.js - perhaps that should be something like a recursive descent instead?
I using babel and React 0.13.1 to build my webapp.
But when I try to add react-google-maps, it break.
I switch back to React 0.12.2 it works, I use console.log
to track reason, it seems the react-google-maps generate some different code with React 0.13.
Note: material-ui seems to use react >= 0.12
not react ^0.12
to let it work with 0.13.
Great library! quick question, is there a way to add listeners only once as is available with the google maps api?
for example:
google.maps.event.addListenerOnce
I have a use case where on mouseover I want to change the icon of the marker. maybe i'm not 'thinking in react' but I don't see a way to do this with this library presently, as when I grab the ref to the marker, the setIcon method is not there. any ideas?
Hey!
How can i use this project as a standalone library in my project? I tried importing the js files from /lib but it didn't work.
Thanks!
Right now, an empty, otherwise useless, div is used to account for the fact that React needs to render to a DOM element. There's actually access to the underlying InfoBox/OverlayView div under instance.div_
which will eliminate the need for that React "crutch".
From disqus thread in dailyjs sharing:
Patrik Stutz:
Be careful when using this component when you render your full page (including head) using react. Google Maps adds script-tags to the head-element, which will confuse react and can lead to rendering problems.
The only workaround I know of, is to put the google map in an iframe... :(
Hello,
Im using the DirectionRenderer component, and i noticed that the rendering performance of it drop really fast depending on the number of waypoint returned by the gmaps direction api.
Ex: with 219 path points the webpage freeze for several seconds. When using vanilla gmap api it draw in a matter of milliseconds.
Ex:
start location 43.124161, 5.9281405000000404
end location : 47.2294142, -1.5732278000000406
This on chrome and on a fast computer.
http://react.rocks/?q=tomchentw
http://dailyjs.com/2014/11/18/react-google-maps-oscar/
http://facebook.github.io/react/blog/2014/11/25/community-roundup-24.html#community-components
https://twitter.com/React_Rocks/status/533075775768252416
https://twitter.com/dailyjs/status/534770948235616256
https://twitter.com/ReactJSnpm/status/535126617354690561
https://twitter.com/reactjs/status/537310487747493888
https://twitter.com/JavaScriptDaily/status/536925782011301888
Hi there,
I have tried to use your component like you used on your examples.
It seems that context.getMap() throw an error.
Do you have some idea of the process to install your component ?
Currently, every components call instance.setOptions(googleMapsConfig)
when componentDidUpdate method is fired, whether googleMapsConfig is changed or not. This will result in an unexpected behaviour.
Hi there! I just started to implement your library in a personal project. Its look great.
I'm trying to initialize a map with custom styles, but I've detected that when you use differents options that there are defined in optionNameList when calling to composeOptions in the _createdMap method they are ignored.
My GoogleMap initializer:
<GoogleMap ref="map" containerProps={{className: 'map-container'}}
styles={mapStyles}
defaultZoom={2}
defaultCenter={{lat: -25.363882, lng: 131.044922}}>
</GoogleMap>
// when are calling to
composeOptions({
defaultZoom: 2,
defaultCenter: {lat: -25.363882, lng: 131.044922},
styles: mapStyles
}, [
"center",
"heading",
"mapTypeId",
"streetView",
"tilt",
"zoom",
]);
// Its returning { zoom: 2, center: {...} } and ignoring styles prop
Thanks in advance :)
Using React 0.13, I get several warnings about owner-based and parent-based contexts differ
.
I haven't been using the Context-feature of React myself, but it seems that components using owner-based context (which react-google-maps apparently is), won't be compatible with the next release of React, which is why React 0.13 is issuing warnings. There's more info here: http://facebook.github.io/react/blog/#owner
component-playground
I've been having troubles running "npm run build" from examples/gh-pages
npm-debug.log outputs the following:
0 info it worked if it ends with ok
1 verbose cli [ 'node', '/Users/lukepint/.node/bin/npm', 'run', 'dev' ]
2 info using [email protected]
3 info using [email protected]
4 verbose node symlink /usr/local/bin/node
5 verbose run-script [ 'predev', 'dev', 'postdev' ]
6 info predev [email protected]
7 info dev [email protected]
8 verbose unsafe-perm in lifecycle true
9 info [email protected] Failed to exec dev script
10 verbose stack Error: [email protected] dev: `npm run clean && webpack-dev-server --content-base ../../public`
10 verbose stack Exit status 1
10 verbose stack at EventEmitter.<anonymous> (/Users/lukepint/.node/lib/node_modules/npm/lib/utils/lifecycle.js:213:16)
10 verbose stack at EventEmitter.emit (events.js:110:17)
10 verbose stack at ChildProcess.<anonymous> (/Users/lukepint/.node/lib/node_modules/npm/lib/utils/spawn.js:24:14)
10 verbose stack at ChildProcess.emit (events.js:110:17)
10 verbose stack at maybeClose (child_process.js:1008:16)
10 verbose stack at Process.ChildProcess._handle.onexit (child_process.js:1080:5)
11 verbose pkgid [email protected]
12 verbose cwd /Users/lukepint/workspace/boomplans/react-google-maps-master/examples/gh-pages
13 error Darwin 14.0.0
14 error argv "node" "/Users/lukepint/.node/bin/npm" "run" "dev"
15 error node v0.12.0
16 error npm v2.8.4
17 error code ELIFECYCLE
18 error [email protected] dev: `npm run clean && webpack-dev-server --content-base ../../public`
18 error Exit status 1
19 error Failed at the [email protected] dev script 'npm run clean && webpack-dev-server --content-base ../../public'.
19 error This is most likely a problem with the gh-pages package,
19 error not with npm itself.
19 error Tell the author that this fails on your system:
19 error npm run clean && webpack-dev-server --content-base ../../public
19 error You can get their info via:
19 error npm owner ls gh-pages
19 error There is likely additional logging output above.
20 verbose exit [ 1, true ]
In addition, I found this in the output of the run:
{ file: '/Users/lukepint/workspace/boomplans/examples/gh-pages/node_modules/bootstrap-sass/assets/stylesheets/bootstrap/mixins/_grid.scss' }
/Users/lukepint/workspace/boomplans/examples/gh-pages/node_modules/webpack-dev-server/node_modules/webpack-dev-middleware/middleware.js:85
if(err) throw err;
^
TypeError: tmp/server.js
--------------------------------------------------------------------------------options must be an object
at TypeError (native)
at Object.exports.createScript (vm.js:44:10)
at module.exports (/Users/lukepint/workspace/boomplans/examples/gh-pages/node_modules/eval/eval.js:55:8)
at IsomorphicReactPluginFactory.evaluate (/Users/lukepint/workspace/boomplans/examples/gh-pages/IsomorphicReactPluginFactory.js:56:12)
at IsomorphicReactPluginFactory.runCompilation (/Users/lukepint/workspace/boomplans/examples/gh-pages/IsomorphicReactPluginFactory.js:68:32)
at IsomorphicReactPluginFactory.receivedClientAssets (/Users/lukepint/workspace/boomplans/examples/gh-pages/IsomorphicReactPluginFactory.js:33:10)
at ClientPlugin.<anonymous> (/Users/lukepint/workspace/boomplans/examples/gh-pages/IsomorphicReactPluginFactory.js:97:24)
at Tapable.applyPluginsAsync (/Users/lukepint/workspace/boomplans/examples/gh-pages/node_modules/webpack/node_modules/tapable/lib/Tapable.js:71:13)
at Tapable.Compiler.emitAssets (/Users/lukepint/workspace/boomplans/examples/gh-pages/node_modules/webpack/lib/Compiler.js:216:7)
at Watching.<anonymous> (/Users/lukepint/workspace/boomplans/examples/gh-pages/node_modules/webpack/lib/Compiler.js:45:18)
--------------------------------------------------------------------------------
Can you provide any insight into why this might be failing?
Thanks
Is there any substantial disadvantages in https://github.com/pieterv/react-googlemaps which was started in September'14.
What are the advantages of your version?
Hello,
I am trying to install on a VVV (vagrant) installation (with no alterations, as is from the VVV github master) and it fails. Is there something that I am missing? Thanks!
This is the command:
vagrant@vvv:/vagrant/www/projects/react-google-maps$ npm install
This is what I get:
npm WARN optional dep failed, continuing [email protected]
npm ERR! Linux 3.13.0-52-generic
npm ERR! argv "node" "/usr/bin/npm" "install"
npm ERR! node v0.10.37
npm ERR! npm v2.9.1
npm ERR! path /vagrant/www/projects/react-google-maps/node_modules/tomchentw-npm-dev/node_modules/conntional-changelog/node_modules/lodash.assign/node_modules/lodash._basecreatecallback/node_modules/lodh._setbinddata/package.json.1ec3a17b60468f8c56d9573322440253
npm ERR! code EPERM
npm ERR! errno 50
npm ERR! Error: EPERM, open '/vagrant/www/projects/react-google-maps/node_modules/tomchentw-npm-dev/ne_modules/conventional-changelog/node_modules/lodash.assign/node_modules/lodash._basecreatecallback/ne_modules/lodash._setbinddata/package.json.1ec3a17b60468f8c56d9573322440253'
npm ERR! { [Error: EPERM, open '/vagrant/www/projects/react-google-maps/node_modules/tomchentw-npm-d/node_modules/conventional-changelog/node_modules/lodash.assign/node_modules/lodash._basecreatecallba/node_modules/lodash._setbinddata/package.json.1ec3a17b60468f8c56d9573322440253']
npm ERR! errno: 50,
npm ERR! code: 'EPERM',
npm ERR! path: '/vagrant/www/projects/react-google-maps/node_modules/tomchentw-npm-dev/node_modulesonventional-changelog/node_modules/lodash.assign/node_modules/lodash._basecreatecallback/node_modulesodash._setbinddata/package.json.1ec3a17b60468f8c56d9573322440253' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.
npm ERR! Linux 3.13.0-52-generic
npm ERR! argv "node" "/usr/bin/npm" "install"
npm ERR! node v0.10.37
npm ERR! npm v2.9.1
npm ERR! path npm-debug.log.0ddeb4ce98c3b7b42b152ccb02139d11
npm ERR! code ETXTBSY
npm ERR! errno 62
npm ERR! ETXTBSY, rename 'npm-debug.log.0ddeb4ce98c3b7b42b152ccb02139d11'
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! https://github.com/npm/npm/issues
npm ERR! Please include the following file with any support request:
npm ERR! /vagrant/www/projects/react-google-maps/npm-debug.log
When I tried to make this a gem on rails-assets.org, I got this error message. Can it be fixed? Thanks.
This component doesn't define main assets in bower.json.
Please open new pull request in component's repository:
https://github.com/tomchentw/react-google-maps
This code makes excessive use of an undocumented, unsupported feature in React: the context. It stores, for example, the reference to the Google Maps objects in the context.
This makes using multiple maps on the page extremely hard/impossible. If you have a Marker, which Map does the Marker get added to? Well, that's going to depend on which map is in the React context right now.
React context is in general a big no-no.
There is no Rectangle
shape available (just Circle
, Polygon
, and Polyline
)
It should be fairly simple to add a new wrapping component in the same vein as Polygon
to allow for <Rectangle />
to be created.
I'll try and get a PR up for this tomorrow, but happy for someone to beat me to it ๐
Inspired by #81 , I think it would be great if we could provide a <Component>
that will load this module.
Since System.js
seems to be the best, future proof library ATM, I think it would be great to implement this feature with it. However, it seems to be too overkilled for a simple feature to use ~13KB in minified, ungzipped bundle.
I was thinking if we could provide a tiny polyfill when System
is not exist:
const loadScript = System.import || function (url) {
return new Promise((resolve, reject) => {
// add <script> tag to <head> and resolve when loaded.
});
}
// Use it like this
loadScript("https://maps.googleapis.com/maps/api/js").then(fn);
Is this polyfill matches what System.js do? Or will there be any problem associate with it?
https://github.com/whatwg/loader/issues/43
https://github.com/systemjs/systemjs/issues/384
React is moving to ES6 classes and away from React.createClass()
, but mixins do not work with ES6 classes and are being deprecated.
The solution? Move to wrapper components.
component-playground
On examples/gh-pages
Hi! I just found this repo and am implementing it in a project I'm working on. Runs very smooth, thanks for this!
However, I want to apply my own map style to the map, and I fail to see how/where I can do that. Any ideas on how/if that can be done?
Also, where do I put other props for the map/markers, like icon for marker, assigning an info window to it and opening it on click etc? I noticed there seems to be a component called InfoWindow, but I couldn't find any documentation about it.
Thanks in advance, and thanks for the great repo!
This can be seen in the demo page. Zoom in, then click to add a marker. It will zoom back out. Same thing for removing markers.
Hello guys,
Really great components, but I want to listen event dragend
on Marker, I tried like this:
<Marker position={origin}
googleMapsApi={googleMapsApi}
dragend={this.handleMarkerChanged}
key={'marker-origin'}
draggable={true}
animation={2} />
But, it not work. So, how can I addListener events on Marker component?
Thanks.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.