MapboxGL标记在React中保留地图容器

时间:2017-01-20 18:50:39

标签: javascript reactjs mapbox-gl

我正在使用React / MapboxGL应用程序,并且每当我移动地图时,我的标记都会出现问题而离开指定地图区域的边界。我觉得可能还有一些其他更大的底层React渲染主体,我不完全理解这对我造成了这个问题。任何帮助将非常感激。谢谢!

此外,每当我点击地图时,我都注意到地图上有一个蓝色的可突出边框,这在我见过的任何教程/示例中都没有。这让我进一步相信它是如何将mapbox-gl与React集成的。

以下是我使用的组件 -

主要组件

import React from 'react';
import ReactDOM from 'react-dom';
import List from './List.jsx';
import MapComponent from './Map.jsx';
import Header from './Header.jsx';

const appConstants = require('../constants/appConstants');
const host = 'http://localhost:8020';
const socket = io(host);

let key = 0;

class MainComponent extends React.Component {

  constructor() {
     super();
     this.state = {
        events: []
    };
  }

componentWillMount() {
    socket.on('new event', (event) => this._handleStateChange(event));
}

render() {
    return (
        <div>
            <div className="headerContainer">
                <Header name={appConstants.appHeader}></Header>
            </div>
            <div className="flexContainer">
                <div className="tabContainer">Tabs on Tabs</div>
                <div className="mapContainer">
                    <MapComponent events={this.state.events} heading={appConstants.mapHeader}></MapComponent>
                </div>
                <div className="eventContainer">
                    <List events={this.state.events}></List>
                </div>
            </div>
        </div>
    );
}

    _handleStateChange(event) {
        let newEvent = {
            browserName: event.new_val.browserName,
            location: event.new_val.location,
            osName: event.new_val.osName,
            key: key,
            eventName: event.new_val.event,
            interval: event.new_val.interval
        };

        key++;

        this.state.events.unshift(newEvent);
        let events = this.state.events.slice(0, 10);

        this.setState({events});
    }
}

ReactDOM.render(<MainComponent />, document.getElementById('main'));

地图组件

class MapComponent extends React.Component {

    constructor() {
        super();
    };

    componentDidMount() {
        /* On first load - center */
        map = new mapboxgl.Map({
            container: 'map',
            style: mapConstants.style,
            center: mapConstants.hqCoordinates,
            zoom: 11
        });

        /* on initial load setup the location + icon */
        map.on('load', function () {

            const el = document.createElement('img');
            el.className = 'marker';
            el.style.backgroundImage = 'url(./assets/images/banana.png)';
            el.style.width = mapConstants.markerWidth;
            el.style.height = mapConstants.markerHeight;

            new mapboxgl.Marker(el)
               .setLngLat(mapConstants.hqCoordinates)
               .addTo(map);
        });

   }

    /* called when the props are updated */
    componentWillUpdate() {
       this._handleEventChange(this.props.events)
    }


    /* helper functions */
    _handleEventChange(events) {
        /* get most recent event and fly there */
        const mostRecentEvent = events[0];

        /* map box coordinates: [lng, lat ] */
        const mostRecentLocation = mostRecentEvent.location.split(',').reverse();

        map.flyTo({
           center: mostRecentLocation,
           zoom: 11
        });

        /* check if data source has been added */
        const existingEvent = map.getSource('mostRecentEvent');

        /* if data source exists, update the data */
        if (existingEvent) {
            existingEvent.setData({
                "type": "Feature",
                "geometry": {
                   "type": 'Point',
                   "coordinates": mostRecentLocation
               },
               "properties": {
                   "title":helperService.getShortEventName(mostRecentEvent.eventName),
                   "icon": mostRecentEvent.browserName.toLowerCase()
                }
            })
        } else {
            /* otherwise this is the first event and we need to add a source & layer */
            map.addSource('mostRecentEvent', {
                "type": "geojson",
                "data": {
                    "type": "Feature",
                    "geometry": {
                         "type": 'Point',
                         "coordinates": mostRecentLocation
                     },
                    "properties": {
                       "title": helperService.getShortEventName(mostRecentEvent.eventName),
                        "icon": mostRecentEvent.browserName.toLowerCase()
                    }
                }
            });

            map.addLayer({
                "id": "mostRecentEvent",
                "type": "symbol",
                "source": "mostRecentEvent",
                "layout": {
                    "icon-image": "{icon}",
                    "text-field": "{title}",
                    "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
                    "text-offset": [0, 0.6],
                    "text-anchor": "top",
                    "text-allow-overlap": true,
                    "text-size": 20
                },
                "paint": {
                    "text-color": '#FF0080'
                }
             });
        }
    }

    render() {
        return (<div>
             <div className="mapHeader">{this.props.heading}</div>
            <div id="map" style={styles.map}></div>
        </div>);
     }

}

   let styles = {
         map: {
           height: '500',
           width: '100%',
           zIndex: 0
  }
};

module.exports = MapComponent;

这个问题的几张图片

centered

after moving the map

0 个答案:

没有答案