UNPKG

google-react-maps

Version:

A more powerfully custom version of the Google Maps Javascript API built for React. Multiple Datalayer support. GEOJSON Enabled.

521 lines (431 loc) 17.8 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Google React Maps Source: components/map.js</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/sunlight.default.css"> <link type="text/css" rel="stylesheet" href="styles/site.cosmo.css"> </head> <body> <div class="navbar navbar-default navbar-fixed-top navbar-inverse"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="index.html">Google React Maps</a> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="navbar-collapse collapse" id="topNavigation"> <ul class="nav navbar-nav"> <li class="dropdown"> <a href="namespaces.list.html" class="dropdown-toggle" data-toggle="dropdown">Namespaces<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="google.maps.html">google.maps</a></li><li><a href="Utils.html">Utils</a></li> </ul> </li> <li class="dropdown"> <a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="Circle.html">Circle</a></li><li><a href="Cluster.html">Cluster</a></li><li><a href="ClusterIconInfo.html">ClusterIconInfo</a></li><li><a href="ClusterIconStyle.html">ClusterIconStyle</a></li><li><a href="Feature.html">Feature</a></li><li><a href="google.maps.LatLngLiteral.html">google.maps.LatLngLiteral</a></li><li><a href="Map.html">Map</a></li><li><a href="Map.InfoWindow.html">Map.InfoWindow</a></li><li><a href="Map.Marker.html">Map.Marker</a></li><li><a href="Map.MarkerCluster.html">Map.MarkerCluster</a></li><li><a href="MapControl.html">MapControl</a></li><li><a href="MarkerClusterer.html">MarkerClusterer</a></li><li><a href="MarkerClustererOptions.html">MarkerClustererOptions</a></li> </ul> </li> <li class="dropdown"> <a href="events.list.html" class="dropdown-toggle" data-toggle="dropdown">Events<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="MarkerClusterer.html#event:click">MarkerClusterer#event:click</a></li><li><a href="MarkerClusterer.html#event:clusteringbegin">MarkerClusterer#event:clusteringbegin</a></li><li><a href="MarkerClusterer.html#event:clusteringend">MarkerClusterer#event:clusteringend</a></li><li><a href="MarkerClusterer.html#event:mouseout">MarkerClusterer#event:mouseout</a></li><li><a href="MarkerClusterer.html#event:mouseover">MarkerClusterer#event:mouseover</a></li> </ul> </li> <li class="dropdown"> <a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="global.html#processPoints">processPoints</a></li> </ul> </li> </ul> <div class="col-sm-3 col-md-3"> <form class="navbar-form" role="search"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="q" id="search-input"> <div class="input-group-btn"> <button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button> </div> </div> </form> </div> </div> </div> </div> <div class="container" id="toc-content"> <div class="row"> <div class="col-md-12"> <div id="main"> <h1 class="page-title">Source: components/map.js</h1> <section> <article> <pre class="sunlight-highlight-javascript linenums">import React from 'react'; import PropTypes from 'prop-types'; import ReactDom from 'react-dom'; import mapsapi from 'google-maps-api'; import {refreshComponentFromProps, isValidMapListener} from '../utils/utils'; /** * See [Google Maps Javascript API]{@link https://developers.google.com/maps/documentation/javascript/3.exp/reference} * @namespace google.maps * @memberof google */ /** * See [LatLngLiteral object specification]{@link https://developers.google.com/maps/documentation/javascript/3.exp/reference#LatLngLiteral} * @class google.maps.LatLngLiteral * @memberof google.maps * * @property {number} lat * @property {number} lng */ /** * The Map Component in the root component for the google maps library. It handles the interface between the google maps javascript api and the implementation of the other components. * @class Map * * @property {string} api-key Required. The javascript api key from your [google console]{@link http://console.developer.google.com}. * @property {object} mapOptions Optional. A google.maps.MapOptions object. * * @property {object} props * @property {function} props.onMount callback(map, maps) Get's called right after the component is done it's initial render. (Key for triggering outside events that require google maps api to be instantiated.) * @property {number} props.zoom * @property {google.maps.LatLngLiteral} props.center * @property {object} props.latLngBounds * @property {google.maps.LatLngLiteral} props.latLngBounds.sw * @property {google.maps.LatLngLiteral} props.latLngBounds.ne */ class Map extends React.Component { constructor(props) { super(props); this.displayName = 'Map'; var _div_id = "map_div_" + Math.floor(Date.now() * Math.random()).toString(); /** * @property {object} state The Map component's internal state. * @property {object} state.maps A google maps javascript api reference. * @property {object} state._div_id The div id of this map. */ this.state = { maps : null, map : null, _div_id } this.listeners = []; this.getGeocoder = this.getGeocoder.bind(this); this.getGoogleMapsApi = this.getGoogleMapsApi.bind(this); this.getGoogleMap = this.getGoogleMap.bind(this); this.getOptions = this.getOptions.bind(this); this.refreshComponentFromProps = refreshComponentFromProps.bind(this); this.centerPropDidChange = this.centerPropDidChange.bind(this); this.boundsPropDidChange = this.boundsPropDidChange.bind(this); this.zoomPropDidChange = this.zoomPropDidChange.bind(this); this.addListener = this.addListener.bind(this); this.removeListeners = this.removeListeners.bind(this); this.setupMapListenerHooks = this.setupMapListenerHooks.bind(this); } /** Gets the instance of the geocoder tied to this google map. */ getGeocoder() { return this.state.geocoder; } /** Gets the google maps api reference from within the component. (Could be used to do google maps api stuff outside of the component) */ getGoogleMapsApi() { return this.state.maps; } /** Gets the google maps instance created by `new maps.Map()` keyword. */ getGoogleMap() { return this.state.map; } getOptions(maps) { var mapOptions = { zoom : 4, mapTypeId : maps.MapTypeId[!this.props.mapType? "ROADMAP" : this.props.mapType], data : null } if(this.props.optionsConstructor) mapOptions = Object.assign(mapOptions, new this.props.optionsConstructor(maps)); return mapOptions; } centerPropDidChange() { var {maps,map} = this.state; var {center} = this.props; if(center) return !new maps.LatLng(center.lat,center.lng).equals(map.getCenter()); else return false; } centerHandleChange() { const center = this.state.map.getCenter(); if(this.props.center.lat != center.lat &amp;&amp; this.props.center.lng != center.lng) { this.state.map.setCenter(this.props.center); } } boundsPropDidChange() { var {bounds} = this.props; if(bounds &amp;&amp; bounds.sw &amp;&amp; bounds.ne) { bounds = new this.state.maps.LatLngBounds(bounds.sw, bounds.ne); } return bounds ? !this.state.map.getBounds().equals(bounds) : false; } boundsHandleChange() { console.log("Bounds Handle Change") var {bounds} = this.props; if(bounds &amp;&amp; bounds.sw &amp;&amp; bounds.ne) { bounds = new this.state.maps.LatLngBounds(bounds.sw, bounds.ne); this.state.map.panToBounds(bounds); } //TODO: Handle bounds change. } zoomPropDidChange() { var {map} = this.state; var {zoom} = this.props; return typeof zoom !== 'undefined' ? (zoom != map.getZoom()) : false; } zoomHandleChange() { var {map} = this.state; var {zoom} = this.props; try { map.setZoom(zoom); } catch(e) { console.error(e); } } addListener(listener) { this.listeners.push(listener); } removeListeners() { while(this.listeners.length > 0) { this.listeners.pop().remove(); } } setupMapListenerHooks() { var {maps, map} = this.state; if(maps &amp;&amp; map) { this.removeListeners(); var assemble = (name, callback) => this.addListener(maps.event.addListener(map, name, callback)); var props = Object.getOwnPropertyNames(this.props); props.forEach(prop => { if(/^on.*$/.test(prop)) { var action = prop.slice(2, prop.length); //Remove the 'on' in front of the prop-name. if(isValidMapListener(action)) { switch(action.toLowerCase()) { case 'bounds_changed':case 'boundschanged': assemble('bounds_changed', event => { const bounds = map.getBounds()? {ne : map.getBounds().getNorthEast().toJSON(), sw : map.getBounds().getSouthWest().toJSON()} : null; this.props[prop](bounds, event) }); break; case 'center_changed':case 'centerchanged': assemble('center_changed', event => { const center = map.getCenter(); this.props[prop](center, event); }); break; case 'zoom_changed':case 'zoomchanged': assemble('zoom_changed', event => { const zoom = map.getZoom(); this.props[prop](zoom, event); }); default: assemble(action.toLowerCase(), this.props[prop]); break; } } else { if(action.toLowerCase() !== 'mount') { console.warn(new Error("You tried adding " + prop + " which is not a valid action for a &lt;Map /> component.")); } } } }); } } componentDidMount() { var initMapComponentWithLibrary = (maps) => { // window.maps = maps; var mapOptions = this.getOptions(maps); try { var geocoder = new maps.Geocoder(); var map = new maps.Map( ReactDom.findDOMNode(this.refs.map) , mapOptions); map.setCenter(!this.props.center? new maps.LatLng(39.5, -98.35) : new maps.LatLng(this.props.center.lat,this.props.center.lng)); if(this.props.bounds &amp;&amp; this.props.bounds.sw &amp;&amp; this.props.bounds.ne) { const bounds = new maps.LatLngBounds(this.props.bounds.sw, this.props.bounds.ne); map.panToBounds(bounds); } } catch(e) { console.error(e); } this.setState({ map, maps, geocoder }, () => { this.refreshComponentFromProps(); if(typeof this.props.onMount === 'function') { this.props.onMount(this.getGoogleMap(), this.getGoogleMapsApi()); } }); this.setupMapListenerHooks(); } if(this.props["api-key"]) { // if(!window.maps) mapsapi(this.props["api-key"], ['drawing','geometry','places'])().then(initMapComponentWithLibrary); // else // initMapComponentWithLibrary(window.maps); } } componentDidUpdate() { if(this.state.map) { this.refreshComponentFromProps(); this.setupMapListenerHooks();// ?? This may not be necessary. Only on didMount. } } componentWillUnmount() { this.removeListeners(); } render() { var children = []; var controls = []; if(this.state.maps &amp;&amp; this.state.map &amp;&amp; this.props.children) children = React.Children.map(this.props.children, child => child ? React.cloneElement(child, { maps : this.state.maps, map : this.state.map }) : undefined ); if(this.state.maps &amp;&amp; this.state.map &amp;&amp; this.props.controls &amp;&amp; this.props.controls.constructor.name === 'Array') { controls = React.Children.map(this.props.controls, control => control ? React.cloneElement(control, { maps : this.state.maps, map : this.state.map }) : undefined ); } return &lt;div ref="map" id={this.state._div_id} style={this.props.style}> &lt;div>{children}&lt;/div> &lt;div>{controls}&lt;/div> &lt;/div>; } } Map.propTypes = { didMount : PropTypes.func, optionsConstructor : PropTypes.func, "api-key" : PropTypes.string.isRequired, style : PropTypes.object, mapType : PropTypes.string, zoom : PropTypes.number, center : PropTypes.shape({ lat : PropTypes.number, lng : PropTypes.number }), bounds : PropTypes.shape({ sw : PropTypes.shape({ lat : PropTypes.number, lng : PropTypes.number }), ne : PropTypes.shape({ lat : PropTypes.number, lng : PropTypes.number }) }) } export default Map; </pre> </article> </section> </div> </div> <div class="clearfix"></div> </div> </div> <div class="modal fade" id="searchResults"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Search results</h4> </div> <div class="modal-body"></div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div> <footer> <span class="copyright"> This is a Austin Hunt project. </span> <span class="jsdoc-message"> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.0</a> on Tue May 30th 2017 using the <a href="https://github.com/docstrap/docstrap">DocStrap template</a>. </span> </footer> <script src="scripts/docstrap.lib.js"></script> <script src="scripts/toc.js"></script> <script type="text/javascript" src="scripts/fulltext-search-ui.js"></script> <script> $( function () { $( "[id*='$']" ).each( function () { var $this = $( this ); $this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) ); } ); $( ".tutorial-section pre, .readme-section pre" ).each( function () { var $this = $( this ); var example = $this.find( "code" ); exampleText = example.html(); var lang = /{@lang (.*?)}/.exec( exampleText ); if ( lang && lang[1] ) { exampleText = exampleText.replace( lang[0], "" ); example.html( exampleText ); lang = lang[1]; } else { var langClassMatch = example.parent()[0].className.match(/lang\-(\S+)/); lang = langClassMatch ? langClassMatch[1] : "javascript"; } if ( lang ) { $this .addClass( "sunlight-highlight-" + lang ) .addClass( "linenums" ) .html( example.html() ); } } ); Sunlight.highlightAll( { lineNumbers : true, showMenu : true, enableDoclinks : true } ); $.catchAnchorLinks( { navbarOffset: 10 } ); $( "#toc" ).toc( { anchorName : function ( i, heading, prefix ) { var id = $( heading ).attr( "id" ); return id && id.replace(/\~/g, '-inner-').replace(/\./g, '-static-') || ( prefix + i ); }, selectors : "#toc-content h1,#toc-content h2,#toc-content h3,#toc-content h4", showAndHide : false, smoothScrolling: true } ); $( "#main span[id^='toc']" ).addClass( "toc-shim" ); $( '.dropdown-toggle' ).dropdown(); $( "table" ).each( function () { var $this = $( this ); $this.addClass('table'); } ); } ); </script> <!--Navigation and Symbol Display--> <!--Google Analytics--> <script type="text/javascript"> $(document).ready(function() { SearcherDisplay.init(); }); </script> </body> </html>