Google Map Api Marker not showing with Reactjs

与世无争的帅哥 提交于 2019-12-12 10:10:37

问题


I am trying to display a google map with a marker. I am using React.js. The map displays in the correct location, but the marker does not show and I get multiple 'object is not extensible' error in the browser console

The code looks like this

/** @jsx React.DOM */
var Map = React.createClass({
  initialize: function() {
    var lat = parseFloat(this.props.lat);
    var lng = parseFloat(this.props.lon); 
    var myPosition = new google.maps.LatLng(lat,lng);
    var mapOptions = { 
     center: myPosition,
     zoom: 8
    };
    var map = new google.maps.Map(this.getDOMNode(), mapOptions);
    var marker = new google.maps.Marker({position: myPosition, title: 'Hi', map: map});
  },
  componentDidMount: function(){
this.initialize();
  },
  render:function(){
    return <div className="map"/>
  }
});

detailed errors from console:

Uncaught TypeError: Can't add property k, object is not extensible VM3577:92

Uncaught TypeError: Can't add property onerror, object is not extensible main.js:3

Uncaught TypeError: Can't add property k, object is not extensible VM3577:92

Uncaught TypeError: Cannot read property 'style' of undefined VM3577:69

Uncaught TypeError: Can't add property onerror, object is not extensible


回答1:


Craig Savolainen has a nice explanation on using Google Maps as a React Component here, the gist for the example is here. I acomplished the marker render with the following code:

var ExampleGoogleMap = React.createClass({  
    getDefaultProps: function () {
        return {
            initialZoom: 8,
            mapCenterLat: 43.6425569,
            mapCenterLng: -79.4073126,
        };
    },
    componentDidMount: function (rootNode) {
        var mapOptions = {
            center: this.mapCenterLatLng(),
            zoom: this.props.initialZoom
        },
        map = new google.maps.Map(document.getElementById('react-valuation-map'), mapOptions);
        var marker = new google.maps.Marker({position: this.mapCenterLatLng(), title: 'Hi', map: map});
        this.setState({map: map});
    },
    mapCenterLatLng: function () {
        var props = this.props;
        return new google.maps.LatLng(props.mapCenterLat, props.mapCenterLng);
    },
    render: function () {
        return (
            <div className='map-gic'></div>
        );
    }
});

Working jsFiddle



来源:https://stackoverflow.com/questions/23367489/google-map-api-marker-not-showing-with-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!