Giter Site home page Giter Site logo

react-gmaps's Introduction

Build Status

React Gmaps

A Google Maps component for React.js

Features

  • Lazy Google Maps loading
  • Easy to use

Installation

$ npm install react-gmaps --save

Demo

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

Usage

import React from 'react';
import ReactDOM from 'react-dom';
import {Gmaps, Marker, InfoWindow, Circle} from 'react-gmaps';

const coords = {
  lat: 51.5258541,
  lng: -0.08040660000006028
};

const params = {v: '3.exp', key: 'YOUR_API_KEY'};

class App extends React.Component {

  onMapCreated(map) {
    map.setOptions({
      disableDefaultUI: true
    });
  }

  onDragEnd(e) {
    console.log('onDragEnd', e);
  }

  onCloseClick() {
    console.log('onCloseClick');
  }

  onClick(e) {
    console.log('onClick', e);
  }

  render() {
    return (
      <Gmaps
        width={'800px'}
        height={'600px'}
        lat={coords.lat}
        lng={coords.lng}
        zoom={12}
        loadingMessage={'Be happy'}
        params={params}
        onMapCreated={this.onMapCreated}>
        <Marker
          lat={coords.lat}
          lng={coords.lng}
          draggable={true}
          onDragEnd={this.onDragEnd} />
        <InfoWindow
          lat={coords.lat}
          lng={coords.lng}
          content={'Hello, React :)'}
          onCloseClick={this.onCloseClick} />
        <Circle
          lat={coords.lat}
          lng={coords.lng}
          radius={500}
          onClick={this.onClick} />
      </Gmaps>
    );
  }

};

ReactDOM.render(<App />, document.getElementById('gmaps'));

Test

$ npm test

react-gmaps's People

Contributors

bassjacob avatar celsom3 avatar drknoxy avatar elg0nz avatar iest avatar laurenskling avatar lucasmotta avatar marudor avatar maulberto3 avatar michelebertoli avatar mistadikay avatar renatorozas avatar wmertens 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-gmaps's Issues

Using removed Babel 5 option

I tried to use this today but I get an error on my webpack. What happening? I can add info I don't know what thoguh.

    ERROR in ./~/react-gmaps/dist/index.js
    Module build failed: ReferenceError: [BABEL] .../node_modules/react-gmaps/dist/index.js: Using removed Babel 5 option: .../node_modules/react-gmaps/.babelrc.stage - Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets
        at Logger.error (.../node_modules/babel-core/lib/transformation/file/logger.js:39:11)
        at OptionManager.mergeOptions (.../node_modules/babel-core/lib/transformation/file/options/option-manager.js:265:20)
        at OptionManager.addConfig (.../node_modules/babel-core/lib/transformation/file/options/option-manager.js:207:10)
        at OptionManager.findConfigs (.../node_modules/babel-core/lib/transformation/file/options/option-manager.js:413:16)
        at OptionManager.init (.../node_modules/babel-core/lib/transformation/file/options/option-manager.js:461:12)
        at File.initOptions (.../node_modules/babel-core/lib/transformation/file/index.js:194:75)
        at new File (.../node_modules/babel-core/lib/transformation/file/index.js:123:22)
        at Pipeline.transform (.../node_modules/babel-core/lib/transformation/pipeline.js:45:16)
        at transpile (.../node_modules/babel-loader/index.js:14:22)
        at Object.module.exports (.../node_modules/babel-loader/index.js:88:12)
     @ ./src/components/list-page.js 22:18-40

Error on rendering

Hi,
I'm getting the following error on adding the component.
Unhandled promise rejection TypeError: Cannot read property 'setOptions' of null(โ€ฆ)

Here is my component:

import React from 'react';
import {Gmaps, Marker, InfoWindow, Circle} from 'react-gmaps';

export default class GMapBox extends React.Component {
  render() {
    const coords = {
      lat: this.props.lat,
      lng: this.props.lng
    };

    return (
      <Gmaps
        width={'300px'}
        height={'300px'}
        lat={coords.lat}
        lng={coords.lng}
        zoom={12}
        loadingMessage={'Be happy'}
        >
        <Marker
          lat={coords.lat}
          lng={coords.lng}
          draggable={false}
           />
        <InfoWindow
          lat={coords.lat}
          lng={coords.lng}
          content={'Hello, React :)'}/>
        <Circle
          lat={coords.lat}
          lng={coords.lng}
          radius={500}
           />
      </Gmaps>
    );
  }
}
GMapBox.displayName = 'GMapBox';
GMapBox.propTypes = {
  lat: React.PropTypes.number.isRequired,
  lng: React.PropTypes.number.isRequired,
  title: React.PropTypes.string
};

Register API key

How would you recommend registering the required API key when using this package?

There's obviously the <script> tag, but I'm unable to store the key in a private variable and append it to the URL within the HTML file.

Is there a way to do this from within the package?

Event `bounds_changed` is not firing up

Hi,

I'm trying to attach a listener for the bounds_changed event.

In order to achieve this i add to the Gmaps object the event handler in this way :

<Gmaps
   [...]
   onBoundsChanged={this.onBoundsChanged} />

and obviously i create the handler:

onBoundsChanged() {
    console.log('bounds change event!!');
  }

But i'm not getting any log. Any idea?

Thanks

Map recentering on new props

Hey,

Just implementing this module, which is great!

One issue, when moving a marker and saving its location back to the state, it updates the props of the maps center.

Is there a way to stop the map from re-centering, I know you added code to make it happen, but it would be nice if it was optional please :)

Thanks!

bundle.js:41862 Uncaught TypeError: Cannot read property 'Map' of undefined

My component is the following

import React from 'react';
import {render} from 'react-dom';
import {Router, Route, IndexRoute, Link, hashHistory} from 'react-router';
import {Gmaps, Marker, InfoWindow, Circle} from 'react-gmaps';
require('../../../../../secrets.js');

var val = false;
var arrayMapsPoints = [];

var coords = {
    lat: 51.5258541,
    lng: -0.08040660000006028
};

var MapDropdown = React.createClass({
    onMapCreated(map2) {
        map2.setOptions({disableDefaultUI: true});
    },

    onDragEnd(e) {
        console.log('onDragEnd', e);
    },

    onCloseClick() {
        console.log('onCloseClick');
    },

    onClick(e) {
        console.log('onClick', e);
    },
    render() {
        return (
            <div>
                {coords.lat}
                <Gmaps width={'800px'} height={'600px'} lat={coords.lat} lng={coords.lng} zoom={12} loadingMessage={'Be happy'} params={{
                    v: '3.exp',
                    key: google.key
                }} onMapCreated={this.onMapCreated}></Gmaps>

            </div>
        )
    }

});

export default MapDropdown;

Display directions

Hi @MicheleBertoli, is there a way we can render direction on the map e.g. supply a origin and destination locations and draw a path between them?

Add Polygon

Polygon isn't currently added to the API of the project. Is this possible in the feature?

API Keys

Thanks for this great little library, do you guys mind explaining how to configure a legitimate API key here?

Google Maps API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys

Unknown prop 'map' - warning

warning.js:36 Warning: Unknown prop `map` on <span> tag. Remove this prop from the element. For details, see https://fb.me/react-unknown-prop
    in span (created by Gmaps)
    in div (created by Gmaps)
    ...

I have this warning, did you @MicheleBertoli or anyone have already dealt with this?

_reactDom2.default.findDOMNode is not a function

Hi @MicheleBertoli ,
I'm new in React JS and i want to try your library for a project which consists in get position of an Arduino Card connected to a GPS sensor.
The problem is : I can't display the map, and i don't know why, maybe my react version is too old ? I'm in react v0.13

There is my code :
`
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import {Gmaps, Marker, InfoWindow, Circle} from 'react-gmaps';

const coords = {
lat: 51.5258541,
lng: -0.08040660000006028
};

const Data = React.createClass({

onMapCreated(map) {
map.setOptions({
disableDefaultUI: true
});
},

onDragEnd(e) {
console.log('onDragEnd', e);
},

onCloseClick() {
console.log('onCloseClick');
},

onClick(e) {
console.log('onClick', e);
},

render: function() {
return (
<Gmaps
width={'800px'}
height={'600px'}
lat={coords.lat}
lng={coords.lng}
zoom={12}
loadingMessage={'Be happy'}
params={{v: '3.exp', key: GOOGLEKEY}}
onMapCreated={this.onMapCreated}>

<InfoWindow
lat={coords.lat}
lng={coords.lng}
content={'Hello, React :)'}
onCloseClick={this.onCloseClick} />


);
}
});

class Suivi extends Component {

render() {
return (
<div>
<Data />
</div>
);
}
}

export default Suivi;

`

And in my console, i obtain this error :
gmaps.js:81 Uncaught TypeError: _reactDom2.default.findDOMNode is not a function

I already tried to update my react version but unfortunately some other part of my application depend on react v0.13

There is my dependencies in package.json :

"dependencies": { "axios": "^0.7.0", "classnames": "^2.1.5", "express": "^4.13.3", "history": "1.17.0", "mongoose": "~3.6.13", "nodemailer": "^2.4.2", "uni-carousel-react": "^0.1.16", "react": "^0.13.3", "react-dom": "^15.2.1", "react-gmaps": "^1.5.0", "react-redux": "^2.1.2", "react-router": "^1.0.0-rc1", "redux": "^3.0.0", "redux-router": "^1.0.0-beta3", "redux-thunk": "^0.1.0" }, "devDependencies": { "babel": "^5.8.21", "babel-core": "^5.8.22", "babel-loader": "^5.3.2", "redux-devtools": "^2.1.5", "redux-logger": "^2.0.2", "babel-plugin-react-transform": "^1.1.0", "babel-runtime": "^5.8.20", "webpack": "^1.11.0", "style-loader": "^0.8.0", "css-loader": "^0.9.0", "url-loader": "^0.5.6", "file-loader": "0.8.5", "react-transform-hmr": "^1.0.0", "webpack-dev-middleware": "^1.2.0", "webpack-hot-middleware": "^2.2.0", "merge": "^1.2.0", "extract-text-webpack-plugin": "^0.8.2" }
It would be very helpful if you can help me, i'm blocked.
Have a good day :)
PS: Sorry for the code section, i have some trouble with github ^^

update with new props

Great product. What would make it awesome is if it would update the map when my props change. I'm using the InfoWindow who's props can change. The Gmaps render is running but it doesn't take notice of my new props.

Using geolocation

Sorry this is more of a query than an issue I think but how would you go about using Geolocation (as per what's already available in the maps api?

https://developers.google.com/maps/documentation/javascript/examples/map-geolocation

I'm trying to see if there's an event before the map is created but where the google maps api has been lazy loaded and can be used or maybe simply putting a step before loading the map to get the users location is the way to go?

I basically want to use a users location if permitted/available and centre the map on that.

Question: How To show InfoWindow on Marker Click

Hello Again...
just want to ask help if how im going to show the InfoWindow once each marker is click..
Sample:
<Gmaps> this.state.pointsResult.map((g,i) => { let infoClick = () => { return( <InfoWindow key="info-1" lat={g.lat} lng={g.lng} content={'End Point'} /> ) } return ( <Marker onClick={infoClick} key={marker-${i}} lat={g.lat} lng={g.lng} /> ) }) ) : null } </Gmaps>

Thanks in advance

onLoad event?

Is there a way to call a function when the map has fully loaded? I don't want to display "loading..." text or watch the map load the tiles.

Thanks!

Uncaught TypeError: _reactDom2.default.findDOMNode is not a function

I get the following error message in my console:

Uncaught TypeError: _reactDom2.default.findDOMNode is not a function

I'm getting desperate because yours is the 5th React Google Maps component I've tried and none except yours have come even close to working. My boss expects me to have a Google map on our React app and I'm at my wit's end. Thank you so much.

Here is my code:

import {Gmaps, Marker, InfoWindow, Circle} from 'react-gmaps';

const coords = {
  lat: 51.5258541,
  lng: -0.08040660000006028
};

class Maps extends React.Component {
  constructor(props, context) {
    super(props, context);
  }

  onMapCreated(map) {
    map.setOptions({
      disableDefaultUI: true
    });
  }

  onDragEnd(e) {
    console.log('onDragEnd', e);
  }

  onCloseClick() {
    console.log('onCloseClick');
  }

  onClick(e) {
    console.log('onClick', e);
  }

  render() {
    return (
      <Gmaps
        width={'800px'}
        height={'600px'}
        lat={coords.lat}
        lng={coords.lng}
        zoom={12}
        loadingMessage={'Be happy'}
        params={{v: '3.exp'}}
        onMapCreated={this.onMapCreated}>
        <Marker
          lat={coords.lat}
          lng={coords.lng}
          draggable={true}
          onDragEnd={this.onDragEnd} />
        <InfoWindow
          lat={coords.lat}
          lng={coords.lng}
          content={'Hello, React :)'}
          onCloseClick={this.onCloseClick} />
         <Circle
          lat={coords.lat}
          lng={coords.lng}
          radius={500}
          onClick={this.onClick} />
      </Gmaps>
    );
  }
}

module.exports = Maps;

Cannot read property 'getMap' of undefined when using demo snippet

When I used the provided demo snippet:


  render() {
    return (
      <Gmaps 
        ref='Gmaps'
        width={'100%'}
        height={'100%'}
        lat={coords.lat} 
        lng={coords.lng} 
        zoom={12} 
        onMapCreated={this.onMapCreated}
        onClick={this.onClick}>
        <Marker 
          lat={coords.lat} 
          lng={coords.lng} />
      </Gmaps>
    );
  },

  onMapCreated() {
    console.log('onMapCreated', this.refs.Gmaps.getMap());
  }

I was getting Cannot read property 'getMap' of undefined when trying to access this.refs.Gmaps, I changed this to:

  render() {
    return (
              <Gmaps
                ref={ this.onMapCreated }
                width={'100%'}
                height={'100%'}
                lat={coords.lat}
                lng={coords.lng}
                zoom={12}
                onClick={this.onClick}>
                <Marker
                  lat={coords.lat}
                  lng={coords.lng} />
              </Gmaps>
    );
  },

  onMapCreated(component) {
    console.log('onMapCreated', component.getMap());
  }

And it fixed the issue. I assume it wasn't able to get the DOM reference previously. I can submit a PR if you think this is the correct approach.

InfoWindow problems

Hi Michele.

I am having trouble with InfoWindow componentโ€”they are always open by default.

I dynamically populate my map with up to 25 Marker and InfoWindow components. I would like to have an InfoWindow open only when a marker is clicked. Will you please suggest the best way to do this?

If it helps, here is a snippet of my component. But please feel free to ignore it's not helpful.

  handleMarkerClick: function(evt) {
    console.log('need to open the corresponding infowindow');
  },

  render: function() {
    function makeMarker(doctor, i) {
      return (
        <Marker
          key={i}
          lat={doctor.lat}
          lng={doctor.lng}
          onClick={this.handleMarkerClick}
        />
      )
    }

    function makeInfoWindow(doctor, i) {
      return (
        <InfoWindow
          key={i}
          lat={doctor.lat}
          lng={doctor.lng}
          ref={'info-' + doctor.id}
          content={doctor.full_name}
          onCloseClick={this.handleInfoWindowCloseClick}
        />
      )
    }

    const mapData = this.props.map
    const markers = mapData.markers.map(makeMarker, this)
    const infoWindows = mapData.markers.map(makeInfoWindow, this)

    return (
      <div className="sideBar_ElementHolder sideBar_MapElementHolder">
        <div className="sideBar_GoogleMapHolder">
          <div id="googleMapWrapper" className="google-map">
            <Gmaps
              width={'100%'}
              ref="gmaps"
              height={'325px'}
              lat={mapData.options.lat}
              lng={mapData.options.lng}
              onMapCreated={this.onMapCreated}
              loadingMessage={'hiyafromloadingmessage'}
              params={{ v: '3' }}
            >
              {markers}
              {infoWindows}
            </Gmaps>
          </div>
        </div>
      </div>
    )
  }

When going to another route, not re-rendering properly

Hello

Me again, I have found a new bug, maybe you know a solution.
When I got to a new route and go back, the map itself is not re-rendered but I see the Circle & Marker.

Circle & Marker are not centered but at position (0, 0) of the div (not the map itself)

Here is a video of the problem:

http://d.pr/v/14nEb

Thanks :)

How to best call fitBounds()?

Thank you for this making this component.

In my map, I need to dynamically set the bounds, using the fitBounds() method on the instance of google.Maps.map. The map instance is available in onMapCreated().

Is there a way to update my map (call fitBounds()) outside of the onMapCreated() method? For example, can I grab hold of the map instance in one of React's lifecycle methods?

So, to recap, I need to call fitBounds() again, after the map is created.

I'm a bit of a newbie, so I apologize if there's an obvious answer to this question!

React 0.14.x support

I get following warning
Warning: Gmaps.getDOMNode(...) is deprecated. Please use ReactDOM.findDOMNode(instance) instead. when upgraded to react 0.14.x.
What is your plan on supporting react 0.14.x ?

"map.setOptions is not a function"

"map.setOptions is not a function" when i'm trying to set map styles;

    handleMapLoad(map) {
        this._mapComponent = map; 
        map.getZoom(); // 15
        map.setOptions({styles: MAP_STYLE}); // "map.setOptions is not a function"
    }

Map not rerendered correctly after state change

Hi,

I use the Gmaps component this way :

<Gmaps
    ref="gmaps"
    height={'600px'}
    lat={parseFloat(this.state.quizz.districtInfoLat)}
    lng={parseFloat(this.state.quizz.districtInfoLon)}
    zoom={12}
    loadingMessage={'Chargement ...'}
    onMapCreated={this._onMapCreated}>
    <Marker
        lat={parseFloat(this.state.quizz.districtInfoLat)}
        lng={parseFloat(this.state.quizz.districtInfoLon)}
        draggable={false}/>
</Gmaps>

The state may be changing this way (by clicking a button) :

_loadNewQuizz() {
    Axios.get('/api/quizz/new').then(quizz => this.setState({
        quizz: quizz.data,
        quizzResult: null,
        selectedOption: null
    }));
}

When I click the button, the Marker rerenders correctly, but the map is not centered on the new lat and lon :-(

Did I miss something or is it a bug?

Thanks in advance for your help!
Sรฉbastien

Get the coordinates of Marker

I tried doing this.refs.Gmaps.refs.Marker.getPosition().lat() but it says:

Uncaught TypeError: this.refs.Gmaps.refs.Marker.getPosition is not a function

Does the Marker even have a method getPosition()? Does this component have all the methods that a regular Marker would have, like in vanilla JS? Thank you for making this; all the other React Google Map components are very confusing!

My code:

import React, { Component } from 'react';
import {render} from 'react-dom';
import {Gmaps, Marker, InfoWindow} from 'react-gmaps';

class App extends Component {

    constructor() {
        super();
        this.state = {
            coords: {
                lat: 40.6319467,
                lng: -89.0465174
            }
        }
        this.onDragEnd = this.onDragEnd.bind(this);
        this.handleClick = this.handleClick.bind(this);
    }

    onMapCreated(map) {
        map.setOptions({
            disableDefaultUI: true
        });
    }

    onDragEnd(e) {
        console.log('dragged');
    }

    handleClick() {
        console.log(this.refs.Gmaps.refs.Marker.getPosition().lat());
    }

    render() {

        const { coords } = this.state;

        return (
            <div>
                <Gmaps
                    width={'800px'}
                    height={'600px'}
                    lat={coords.lat}
                    lng={coords.lng}
                    zoom={8}
                    loadingMessage={'Loading...'}
                    params={{v: '3.exp', key: 'API_KEY_GOES_HEREEEE'}}
                    onMapCreated={this.onMapCreated}
                    ref="Gmaps">
                    <Marker
                        lat={coords.lat}
                        lng={coords.lng}
                        draggable={true}
                        onDragEnd={this.onDragEnd} 
                        ref="Marker"/>
                </Gmaps>
                <button onClick={this.handleClick}>Click</button>
            </div>
        );
    }
}

render(<App />, document.getElementById('root'));

Terrific memory leaks on remounting

Memory leaks on frequently remounting components

In the case when we use a react-gmaps, say, in kind of "details-view" component, that will mount and unmount frequently, gmaps lead to huge memory leaks.

The good way would be to use a single instance of gmaps, accociated with DOM id of the parent element.

Moreover to that, to support hot-reloading, this instance can be stored in the window scope, and taken from there on component mount

Render react components on map

Hi,

Thanks for a nice easy-to-use package :)

Would it be possible to render custom react components on the map at a specific lat/long? I want to do some animations and so on for markers/info and link them to a filterable list.

Thank you.

Regards,
Riaan

Get the zoom level

hi,

is it possible to get the current zoom level upon the onZoomChanged event?

i attached the event handler in this way :

onZoomChanged={this.onZoomChanged}

but any parameter i add on that function results to be undefined.

Is there a way to change marker icons?

The setIcon function from the maps API is not included, so is there any way to alter a marker icon after it has been set? Could the setIcon functionality be implemented?
I have tried setting intervals for the new iconlinks to be provided but but not succeeded.

Best regards

Is there way to customize InfoWindow style, from javascript etc components ?

 {this.state.animateInfo.map(function(purchase){
                        var timeAgo = that.getPurchaseTimeAgo(purchase.created_at);
                        return (<InfoWindow
                            backgroundColor="#0989ff"

                            lat={purchase.lat}
                            lng={purchase.long}
                            content={purchase.product_name +" " +timeAgo+"s ago"}
                            />);
})}

How can i apply custom style not using "hacky-css"?

Thank You!

@MicheleBertoli thank you for this awesome package!

I lost a day trying to configure a couple of other options but this pretty much worked out of the box.

Map is not re-rendering

Hello

I have this problem that I'm drawing a circle on the map, the circle radius can change and thus the props change.
Can you fix it that the map is re-rendered when props change?

Thanks

Directions some help

Hello there, i trying to add directions on an already drawed map to minimize api requests. The think is directionsDisplay.setMap(map); needs the map object from onMapCreated(map). There is any way to use this map object outside of it onMapCreated? Like on ComponentDidUpdate or something? Or there is any other solution? So i can play with changing direction request and to doesnt have to redraw the map.

const start = new google.maps.LatLng(28.694004, 77.110291);
const end = new google.maps.LatLng(28.72082, 77.107241);

const directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map); // map should be already initialized.

const request = {
        origin : start,
        destination : end,
        travelMode : google.maps.TravelMode.DRIVING
 };

const directionsService = new google.maps.DirectionsService(); 
directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
 });

Adding properties to Marker component

Hi Michele.

I am trying to render a complex marker icon, as Google describes here.

This works:

renderCenterMarker: function () {

  if (typeof this.props.meta.center === 'undefined') {
    return
  }

  const { center } = this.props.meta

  const icon = {
    path: "M 125,5 155,90 245,90 175,145 200,230 125,180 50,230 75,145 5,90 95,90 z",
    fillColor: "#222",
    fillOpacity: .6,
    strokeWeight: 1,
    scale: .25
  }

  return (
    <Marker
      lat={center.lat}
      lng={center.lon}
      icon={icon}
    />
  )
},

However, I need to add an origin property to my icon object:

const icon = {
  ...
  origin: new google.maps.Point(0, 0),
  ...
}

This no longer works. Will you please tell me if there's a way to add this property to the marker?

Question: Multiple Marker Color

Hello,

Just want to ask if i can change the marker on the defined position?
Sample: i want on the point 2, the marker will be the green, and the the rest is circle
<Gmaps ref="gmaps" params={{v: '3.exp', key: variables.gmapsApi}} width={'auto'} height={'600px'} lat={this.state.clickPoints.lat} lng={this.state.clickPoints.lng} onMapCreated={this.onMapCreated} zoom={this.state.gmapsZoom}> {this.state.pointsResult.length > 0 ? ( this.state.pointsResult.map((g,i) => { let icon = { path: google.maps.SymbolPath.CIRCLE, strokeColor: '#FF0000', fillColor: '#FF0000', fillOpacity: 0.8, scale: 5 } if(g.package_status ==null) { return ( <Marker icon={icon} onClick={() => this.toggleInfoWindow(i,g)} key={marker-${i}} lat={g.lat} lng={g.lng} /> ) } else { let colorIcon = "http://maps.google.com/mapfiles/ms/icons/green-dot.png" return ( <Marker icon={colorIcon} onClick={() => this.toggleInfoWindow(i,g)} key={marker-${i}} lat={g.lat} lng={g.lng} /> ) } }) ) : null } {this.state.pointsResult.length > 0 ? ( this.renderInfoWindows() ) : null } </Gmaps>

Thanks in advance.

React component in InfoWindow

Is it possible to have a ReactComponent in InfoWindow with all the React component lifecycle functions, click handlers, etc?

I tried doing this, with the content passed to the InfoWindow being a component rendered to a string. onClick handlers in the component aren't firing.

If so, could you provide a short working example?

Avoid re-rendering of map entities

Hello,

I've been using react-gmaps for a little while, and I've notice that in some use cases, there is no way to prevent certain re-renders of map entities, like <Marker>.

Say for example one would have a component like so:

//mygmapscomponent.jsx

  render() {
      let {height, coords, zoom, markers} = this.props;

      return (
        <div className="gmap-component" style={{ position: 'relative' }}>
          <Gmaps
             width={'100%'}
             height={height}
             lat={coords.lat}
             lng={coords.lng}
             zoom={zoom}
             loadingMessage={'loading'}
             onMapCreated={this.onMapCreated}>
             { this.renderMakers( markers ) }
          </Gmaps>
          { this.renderLegend(this.state.legendItems) }
        </div>
      )
  }


  renderLegend(items) {
    return (
      <div className="map-legend">
        { items.map( this.renderLegendItem, this) }
       </div>
    )
  }

If for some reason the component render() is called again, say because of a change in the lengend state, the markers will also be re-render ( which will make the markers flash/flicker on the map)

This is, from what I can see, because componentDidMount in src\components\entity.js re-sets the entities options (like the google map object)

I would suggest allowing to pass a prop to the entity like shouldUpdate that would prevent that from happening if it would return false, much like react's own shouldComponentUpdate, something like this:

//src/components/entity.js
    componentWillReceiveProps(nextProps) {
      if(typeof this.props.shouldUpdate === "function") {
          if( !this.props.shoudUpdate(this.props, nextProps) )
            return;
      }
      const options = this.getOptions(nextProps);
      this.entity.setOptions(options);
    },

This would prevent allow us to check if we really want the entities to update or not, which in my case would prevent markers/etc from flickering on the map each time the component has to render() for an unrelated reason

Help with InfoWindow

Hi there. I need some help with InfoWindow. I want to open a info window when i click on each marker. I have tried a lot of things but no luck until now.

Adding one marker redraws everything

When i add one marker to the map, its redrawing all markers (blinking).

Code:

    render() {
        // i add some markers on some zoomlevels
        const markers = this.state.data.map((e) => {
            return <Marker key={e.id}
                lat={e.location.lat}
                lng={e.location.lng}
                onClick={this.onEventClick.bind(this, e)} />;
        });

        return (
            <Gmaps
                width="100%"
                height="100%"
                lat={51.5258541}
                loadingMessage="Loading..."
                disableDefaultUI={true}
                lng={-0.08040660000006028}
                onMapCreated={this.onMapCreated.bind(this)}
                maxZoom={18}
                styles={mapStyle}
                backgroundColor="#2b2b2b"
                zoom={2}>{markers}</Gmaps>
        );
    }

Issue when installed as a dependency

Hey, thanks for the great module! A maps react component is desperately needed and yours is the only one which works with 0.13 as far as I can see.

However there is one small issue that prevents it from being used. When react-gmaps is installed as a dependency to another module, no devDependencies are installed from your package.json, and your module needs them to run.

Maybe react and the babel-related modules can be moved to dependencies?

onDragEnd handler gets "unbound" when second Gmap and Marker created

I have a Gmap with a draggable Marker which triggers and action to update state in the onDragEnd event handler, which works great.

When the user double-clicks on the Gmap I open a second Gmap in a react-modal dialog that's larger. The second Marker is also draggable and works fine the first time. When the dialog is closed, the Marker on the first Gmap no longer triggers the onDragEng event, but the second Marker in the dialog Gmap works just fine.

I tried creating two distinct onDragEnd handlers to see if that would help and it didn't. I added names to the maps and markers to ensure everything was indeed distinct and that is true.

The onDragEnd appears to be "bound" according to the react tools before and after the dialog is opened/closed, but it acts differently after the dialog has been opened/closed.

Is there some way to rebind the onDragEnd handler?

screen shot 2016-01-06 at 4 46 18 pm

fullMapOpen: function(event){
        "use strict";

        this.setState({
            modalIsOpen: true
        });
    },

onMapMarkerDragEnd(event) {
        console.log('onDragEnd', event);
        var latLng = {};
        latLng[this.props.latKey] = event.latLng.lat();
        latLng[this.props.lngKey] = event.latLng.lng();
        this.props.onComponentChange(latLng);
    },


render: function(){
        "use strict";

        var availableWidth = (window.innerWidth * 0.86) + 'px';
        var availableHeight = (window.innerHeight * 0.86) + 'px';

        const modalStyles = {
            overlay: {
                backgroundColor: 'rgba(0,0,0,0.6)'
            },
            content : {
                top                   : '50%',
                left                  : '50%',
                right                 : 'auto',
                bottom                : 'auto',
                marginRight           : '-50%',
                transform             : 'translate(-50%, -50%)',
                padding               : '2px'
            }
        };

        return (
            <div id="map" onDoubleClick={this.fullMapOpen}>
                <Gmaps
                    name={'primaryAddressMap'}
                    width={'422px'}
                    height={'100px'}
                    lat={this.props.latitude}
                    lng={this.props.longitude}
                    zoom={17}
                    loadingMessage={'Loading...'}
                    params={{v: '3.exp', libraries: 'places'}}
                    onMapCreated={this.onMapCreated}
                    disableDoubleClickZoom={true}
                >
                    <Marker
                        name={'placeMarker'}
                        lat={this.props.latitude}
                        lng={this.props.longitude}
                        draggable={true}
                        onDragEnd={this.onMapMarkerDragEnd}
                    />
                </Gmaps>
                <Modal
                    isOpen={this.state.modalIsOpen}
                    onRequestClose={this.fullMapClose}
                    style={modalStyles} >
                        <div style={{position: 'absolute', zIndex: 100, top: 10, left: 0, right: 0, height: 0, textAlign: 'center'}}>
                            <input type="text" id="place-search" placeholder="Search" style={{ marginTop: 2, width: 300 }}/>
                        </div>
                        <Gmaps
                            name={'primaryAddressMapFull'}
                            width={availableWidth}
                            height={availableHeight}
                            lat={this.props.latitude}
                            lng={this.props.longitude}
                            zoom={17}
                            loadingMessage={'Loading...'}
                            params={{v: '3.exp'}}
                            onMapCreated={this.onMapCreated}
                            disableDoubleClickZoom={true}
                        >
                            <Marker
                                name={'placeMarkerFull'}
                                lat={this.props.latitude}
                                lng={this.props.longitude}
                                draggable={true}
                                onDragEnd={this.onMapMarkerDragEnd}
                            />
                        </Gmaps>
                </Modal>
            </div>
        );
    }

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.