ReactJS實踐:在react框架中使用Google Maps

Bulid Web application use Google Maps

此文章根據Tutorialzine教程實踐,具體代碼可參考Githubhtml

React.js

自正式發佈以來,一直都是熱門話題就很少討論了,官方教程可參考React中文社區或者加入由@題葉推廣的React-China社區react

React組件結構設計

  • App : 最主要的部分,它包含用於能夠由像搜索的用戶執行的操做的方法,增長一個位置到收藏夾等等。的其它組份內嵌套
  • CurrentLocation : 呈如今地圖中的當前被訪問的地址。地址能夠經過點擊星標能夠添加或刪除收藏夾
  • LocationList : 展現用戶Start的LocationItem
  • LocationItem : 是一個單獨的位置。當它被點擊,其相應的地址被搜索到並在地圖上突出顯示
  • Map : 集成了GMaps實現庫,並呈現從谷歌地圖的地圖
  • Search : 是纏繞在搜索表單的成分。當它被提交,搜索位置被觸發
    illustration.png

具體代碼實現

App.js

var React = require('react');
var Search = require('./Search');
var Map = require('./Map');
var CurrentLocation = require('./CurrentLocation');
var LocationList = require('./LocationList');

var App = React.createClass({

    getInitialState(){

        // 使用localStorage(本地存儲)存儲喜好的位置

        var favorites = [];

        if(localStorage.favorites){
            favorites = JSON.parse(localStorage.favorites);
        }

        // 默認初始化地址是巴黎

        return {
            favorites: favorites,
            currentAddress: 'Paris, France',
            mapCoordinates: {
                lat: 48.856614,
                lng: 2.3522219
            }
        };
    },

    toggleFavorite(address){

        if(this.isAddressInFavorites(address)){
            this.removeFromFavorites(address);
        }
        else{
            this.addToFavorites(address);
        }

    },

    addToFavorites(address){

        var favorites = this.state.favorites;

        favorites.push({
            address: address,
            timestamp: Date.now()
        });

        this.setState({
            favorites: favorites
        });

        localStorage.favorites = JSON.stringify(favorites);
    },

    removeFromFavorites(address){

        var favorites = this.state.favorites;
        var index = -1;

        for(var i = 0; i < favorites.length; i++){

            if(favorites[i].address == address){
                index = i;
                break;
            }

        }

        // 若是用戶點擊取消start,從喜歡的arra中刪除它

        if(index !== -1){

            favorites.splice(index, 1);

            this.setState({
                favorites: favorites
            });

            localStorage.favorites = JSON.stringify(favorites);
        }

    },

    isAddressInFavorites(address){

        var favorites = this.state.favorites;

        for(var i = 0; i < favorites.length; i++){

            if(favorites[i].address == address){
                return true;
            }

        }

        return false;
    },

    searchForAddress(address){

        var self = this;

        // 這裏是調用Google Maps API的部分,將會使用到Map.js的GMaps' geocode functionality

        GMaps.geocode({
            address: address,
            callback: function(results, status) {

                if (status !== 'OK') return;

                var latlng = results[0].geometry.location;

                self.setState({
                    currentAddress: results[0].formatted_address,
                    mapCoordinates: {
                        lat: latlng.lat(),
                        lng: latlng.lng()
                    }
                });

            }
        });

    },

    render(){

        return (

            <div>
                <h1>Your Google Maps Locations</h1>

                <Search onSearch={this.searchForAddress} />

                <Map lat={this.state.mapCoordinates.lat} lng={this.state.mapCoordinates.lng} />

                <CurrentLocation address={this.state.currentAddress} 
                    favorite={this.isAddressInFavorites(this.state.currentAddress)} 
                    onFavoriteToggle={this.toggleFavorite} />

                <LocationList locations={this.state.favorites} activeLocationAddress={this.state.currentAddress} 
                    onClick={this.searchForAddress} />

            </div>

        );
    }

});

module.exports = App;

CurrentLocation.js

var React = require('react');

var CurrentLocation = React.createClass({

    toggleFavorite(){
        this.props.onFavoriteToggle(this.props.address);
    },

    render(){

        var starClassName = "glyphicon glyphicon-star-empty";

        if(this.props.favorite){
            starClassName = "glyphicon glyphicon-star";
        }

        return (
            <div className="col-xs-12 col-md-6 col-md-offset-3 current-location">
                <h4 id="save-location">{this.props.address}</h4>
                <span className={starClassName} onClick={this.toggleFavorite} aria-hidden="true"></span>
            </div>
        );
    }

});

module.exports = CurrentLocation;

LocationList.js

var React = require('react');
var LocationItem = require('./LocationItem');

var LocationList = React.createClass({

    render(){

        var self = this;

        var locations = this.props.locations.map(function(l){

            var active = self.props.activeLocationAddress == l.address;

            // 在這個function中將會回調一個onClick
            // LocationList 顯示每一個 LocationItem.

            return <LocationItem address={l.address} timestamp={l.timestamp} 
                    active={active} onClick={self.props.onClick} />
        });

        if(!locations.length){
            return null;
        }

        return (
            <div className="list-group col-xs-12 col-md-6 col-md-offset-3">
                <span className="list-group-item active">Saved Locations</span>
                {locations}
            </div>
        )

    }

});

module.exports = LocationList;

LocationItem.js

var React = require('react');
var LocationItem = require('./LocationItem');
var moment = require('moment');

var LocationItem = React.createClass({

    handleClick(){
        this.props.onClick(this.props.address);
    },

    render(){

        var cn = "list-group-item";

        if(this.props.active){
            cn += " active-location";
        }

        return (
            <a className={cn} onClick={this.handleClick}>
                {this.props.address}
                <span className="createdAt">{ moment(this.props.timestamp).fromNow() }</span>
                <span className="glyphicon glyphicon-menu-right"></span>
            </a>
        )

    }

});

module.exports = LocationItem;

Map.js

var React = require('react');

var Map = React.createClass({

    componentDidMount(){ 
        this.componentDidUpdate();
    },

    componentDidUpdate(){

        if(this.lastLat == this.props.lat && this.lastLng == this.props.lng){
            return;
        }

        this.lastLat = this.props.lat;
        this.lastLng = this.props.lng

        var map = new GMaps({
            el: '#map',
            lat: this.props.lat,
            lng: this.props.lng
        });

        // Adding a marker to the location we are showing

        map.addMarker({
            lat: this.props.lat,
            lng: this.props.lng
        });
    },

    render(){

        return (
            <div className="map-holder">
                <p>Loading...</p>
                <div id="map"></div>
            </div>
        );
    }

});

module.exports = Map;

Search.js

var React = require('react');

var Search = React.createClass({

    getInitialState() {
        return { value: '' };
    },

    handleChange(event) {
        this.setState({value: event.target.value});
    },

    handleSubmit(event){

        event.preventDefault();

        // 當提交表單時,調用傳遞到組件的onSearch回調

        this.props.onSearch(this.state.value);

        // Unfocus文本輸入字段
        this.getDOMNode().querySelector('input').blur();
    },

    render() {

        return (
            <form id="geocoding_form" className="form-horizontal" onSubmit={this.handleSubmit}>
                <div className="form-group">
                    <div className="col-xs-12 col-md-6 col-md-offset-3">
                        <div className="input-group">
                            <input type="text" className="form-control" id="address" placeholder="Find a location..." 
                            value={this.state.value} onChange={this.handleChange} />
                            <span className="input-group-btn">
                                <span className="glyphicon glyphicon-search" aria-hidden="true"></span>
                            </span>
                        </div>
                    </div>
                </div>
            </form>
        );

    }
});

module.exports = Search;

main.js

var React = require('react');
var App = require('./components/App');

React.render(
  <App />,
  document.body
);

總結

從一個初學者的佳都來看,使用React最重要的就是Compoent結構設計,還有就是被調用組件與組件之間的props,state和回調事件函數,附一張結構圖幫助理解結構設計
圖片描述git

相關文章
相關標籤/搜索