React-google-maps: Google Map setCenter and setPosition issue

Created on 20 Oct 2016  路  5Comments  路  Source: tomchentw/react-google-maps

InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number

InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number

`import * as React from "react";
var config = require("./Config");
var $ = require('jquery');
var _this;
var userDetails = require("./api/UserDetails");
var _ = require("lodash")

const { Accordion,Panel,Row, Col } = require("../../../../../../node_modules/react-bootstrap");
import App from '../App'
var GoogleMapLib = require("../../../../../../node_modules/react-google-maps");
var GoogleMap = GoogleMapLib.GoogleMap;
var withGoogleMap = GoogleMapLib.withGoogleMap;
var Marker = GoogleMapLib.Marker;
var InfoWindow = GoogleMapLib.InfoWindow;
const PopUpInfoWindowExampleGoogleMap = withGoogleMap(props => (
  <GoogleMap
    defaultZoom={4}
    center={props.center}
  >
    {props.markers.map((marker, index) => (
      <Marker
        key={index}
        position={marker.position}
        onClick={() => props.onMarkerClick(marker)}
      >
        {/*
          Show info window only if the 'showInfo' key of the marker is true.
          That is, when the Marker pin has been clicked and 'onCloseClick' has been
          Successfully fired.
        */}
        {marker.showInfo && (
          <InfoWindow onCloseClick={() => props.onMarkerClose(marker)}>
            <div>{marker.infoContent}</div>
          </InfoWindow>
        )}
      </Marker>
    ))}
  </GoogleMap>
));

const INITIAL_CENTER = { lat: -25.363882, lng: 131.044922 };
import ReferFriend  from "./ReferFriend";
var ProductDetails = React.createClass({
  getInitialState:function(){
    return{
      appended: '',
      isLoding:'none',
      cordinates:'',
      morelikethis: '',
      merchantCollection:'',
      getParent: false,
      acoordianData:'',
      center: {
      lat: -25.363882,
      lng: 131.044922,
      },
      markers: [
      {
        position: {
                  lat: -27.363882,
                  lng: 137.044922
                },
        showInfo: false,
        infoContent: (
          <svg
            id="Layer_1"
            xmlns="http://www.w3.org/2000/svg"
            width="16"
            height="16"
            viewBox="0 0 16 16"
          >
          </svg>
        ),
      },
      {
        position: {
                  lat: -23.363882,
                  lng: 129.044922
                }, 
        showInfo: false,
        infoContent: (
          <svg
            id="Layer_1"
            xmlns="http://www.w3.org/2000/svg"
            width="16"
            height="16"
            viewBox="0 0 16 16"
          >

          </svg>
        ),
      },
    ],
      zoom: 9,
    };
  },
  // componentWillReceiveProps: function() {

  // },


  _renderInfoWindow: function(ref, marker) {
    return (
      <InfoWindow key={ref + '_info_window'}>
          <p>Test</p>
      </InfoWindow>
    );
  },

  _onMarkerMouseOver: function(index, event) {
    var update = {};
    update[index] = {
      $merge: {

        showInfo: true
      }
    };

    var changedMarkers = React.addons.update(this.state.markers, update);
    this.setState({ markers: changedMarkers });
  },

  _onMarkerMouseOut: function(index, event) {
    var update = {};
    update[index] = {
      $merge: {

        showInfo: false
      }
    };

    var changedMarkers = React.addons.update(this.state.markers, update);
    this.setState({ markers: changedMarkers });
  },


  contextTypes: {
    router: React.PropTypes.object.isRequired
  },

  /*Map related stuff*/


  handleMapLoad:function(map) {
    this._mapComponent = map;
    if (map) {
      console.log(map.getZoom());
    }
  },

  /*
   * This is called when you click on the map.
   * Go and try click now.
   */
  handleMapClick: function(event) {
    const nextMarkers = [
      ...this.state.markers,
      {
        position: event.latLng,
        defaultAnimation: 2
         // Add a key property for: http://fb.me/react-warning-keys
      },
    ];
    this.setState({
      markers: nextMarkers,
    });

    if (nextMarkers.length === 3) {
      this.props.toast(
        `Right click on the marker to remove it`,
        `Also check the code!`
      );
    }
  },

  handleMarkerRightClick:function(targetMarker) {
    /*
     * All you modify is data, and the view is driven by data.
     * This is so called data-driven-development. (And yes, it's now in
     * web front end and even with google maps API.)
     */
    const nextMarkers = this.state.markers.filter(marker => marker !== targetMarker);
    this.setState({
      markers: nextMarkers,
    });
  },

  /*Map related stuff end here*/


  componentWillMount:function(){
    var geoDetails = userDetails.getUserGeoInfo();
    if(geoDetails){
      this.setState({center:[geoDetails.lat,geoDetails.lng]});
      var lat = geoDetails.lat;
      var lng =  geoDetails.lng;
    }else {
      var lat = null;
      var lng =  null;
    }
    this.setState({cordinates:geoDetails});
    $.ajax({
      url: config.magentoBaseUrl+config.MORE_LIKE_THIS,
      dataType: 'json',
      cache: false,
      type: 'POST',
      data:{
        category_name: this.props.productInfo.category_name,
        brand: this.props.productInfo.brand,
        product_category_ids: this.props.productInfo.product_category_ids,
        _id: this.props.productInfo._id,
        lat:lat,
        lng:lng,
        merchant_id:this.props.productInfo.merchant_id,
        storename:this.props.productInfo.store_name
      },
      success: function(data) {
        if(data.productData){
          this.setState({morelikethis:data.productData})
          var merchantData = JSON.parse(data.merchantData);
          if(merchantData){
             this.setState({acoordianData:merchantData});
              var markers = merchantData.map(function(item, i) {
              return {
                position: {
                  lat: item.latitude,
                  lng: item.longitude
                },
                item: item.merchant_name
              }
            }.bind(this));
            this.setState({markers:markers})
          }

      }
    }.bind(this),
      error: function(xhr, status, err) {

      }.bind(this)
    });
  },
  getAccordianData:function(merchantData){
    if(merchantData){
      return merchantData.map(function(store, i){
               return <Panel header={store.storename} eventKey={i} className="store-title">
                   <div className="store-details-locator">
                   <div className="store-distance-miles">{parseInt(store.distance)} &nbsp;miles</div>
                   <div>{store.address1},&nbsp;{store.city},&nbsp;{store.zip}</div>
                   <div className="link-color">{store.telephone}</div>
                   <div><span className="detail-show-bold">Hours:</span>{store.working_hours}</div> 
                  </div>
                </Panel>
         })
    }   
  },
  getHome:function(){
    this.setState({getParent:true});
  },
  render(){
//     var containerProps = {
//       className: 'items-map'
//     };

    return(
      <div>
       {!this.state.getParent ?
        <div>
        <div>
         <div id="map-canvas">
         <PopUpInfoWindowExampleGoogleMap
        containerElement={
          <div style={{ height: `100%` }} />
        }
        mapElement={
          <div style={{ height: `100%` }} />
        }
        center={this.state.center}
        markers={this.state.markers}
        onMarkerClick={this.handleMarkerClick}
        onMarkerClose={this.handleMarkerClose}
      />
         </div>
          <div className="container">
            <div className="row">
                 <div className="hidden-xs col-sm-3 col-md-3 col-lg-3 product-store-locator-div">
                  <div className="stiky-store-locator-div filter">
                      <div className="store-locator-section-title">
                        <span>Store Locator</span>
                      </div>
                      <hr className="store-locator-title-hr"/>

                      <div className="panel-group panel-store-locator" role="tablist" >
                          <Accordion>
                            {this.getAccordianData(this.state.acoordianData)}
                          </Accordion>

                        </div>
                    </div>
                 </div>
             <div className="col-sm-9 col-md-9 col-lg-9 product-details-div">
              <div className="product-details-top-section">
                <div className="row breadcrum-div">
                    <div className="col-xs-12 col-sm-12 col-md-12 col-lg-12 breadcrumbs-title">
                    <span className="icon-Arrow-Left">
                      <a href="#" onClick={()=>this.getHome()} className="details-page-back-link">Back To Search Result Page</a>
                    </span>
                    </div>
                </div>
              </div>

              <div className="row product-details-row-div">
                <div className="col-xs-12 col-sm-6 col-md-5 col-lg-4">
                    <div className="product-details-image-display-div center-block">
                      <div className="dummy-placeholder"></div>
                      <div className="product-details-display-section-style center-block">
                          <img src={this.props.productInfo.product_image} className="img-responsive" alt="product image"/>
                      </div>
                    </div>
                </div>
                <div className="col-xs-12 col-sm-6 col-md-7 col-lg-5">
                    <div className="product-details-outer-div" >
                      <div className="product-details-top-div">
                          <div className="product-brand-name-div">
                            <div className="product-details-brand-name">{this.props.productInfo.brand} </div>
                            <div className="product-details-product-name">{this.props.productInfo.product_name}</div>
                          </div>
                          <div className="product-details-store-name">{this.props.productInfo.store_name}</div>
                          <div className="old-price">
                            <span className="product-listing-details-old-price-div-less">$ {this.props.productInfo.actual_price}</span>&nbsp;&nbsp;
                            <span className="product-listing-details-price-div"></span>
                          </div>
                          <hr className="madal-hr-gray"/>
                          <hr className="modal-hr-white"/>
                          <div className="product-details-description">
                            <div className="product-details-description-content">
                                <div className="product-details-description-title">Description</div>
                                {this.props.productInfo.long_description}
                            </div>
                          </div>
                      </div>
                      <div className="product-details-bottom-div">
                          <div className="buy-from-retailer-btn-div">
                            <a target="_blank" href={this.props.productInfo.retailer_url} >
                            <button type="button" className="btn buy-from-retailer-btn">
                            <span className="btn-detail-style">BUY NOW</span>
                            </button>
                            </a>
                          </div>
                          <div className="add-to-list-btn-div">
                            <button className="btn add-to-list-btn get-alert-detail-page" ><span className="glyphicon glyphicon-bell add-to-list-btn-span"></span><span className="btn-detail-style">GET SALE ALERT</span></button>
                          </div>
                          <div className="button-seprator">&nbsp;</div>
                          <div className="add-to-list-btn-div">
                            <button type="button" className="btn add-to-list-btn"><span className="glyphicon glyphicon-heart add-to-list-btn-span" aria-hidden="true"></span>ADD TO LIST</button>
                          </div>
                      </div>
                    </div>
                </div>
                <div className="col-xs-12 col-sm-12 col-md-12 col-lg-3">
                    <div className="product-details-filter-share-div center-block">
                      <div className="social-network-div">
                          <div className="product-details-social-network-div">
                            <div className="product-details-filter-title">
                                <span>Share</span>
                            </div>
                            <hr className="product-details-filter-title-hr"/>
                            <div className="social-list">

                                <ReferFriend {...this.props}/>

                                <a href={"https://twitter.com/home?status=Check out the Product on Xwalker at &nbsp;-&nbsp; "+this.props.productInfo.product_url} className="btn btn-social-icon btn-social-twitter">
                                 <i className="fa fa-twitter"></i>
                                </a>
                                <a href={"https://www.facebook.com/sharer/sharer.php?u="+this.props.productInfo.product_url} className="btn btn-social-icon btn-social-facebook">
                                 <i className="fa fa-facebook"></i>
                                </a>
                                <a href={"https://plus.google.com/share?url="+this.props.productInfo.product_url} className="btn btn-social-icon btn-social-google-plus">
                                 <i className="fa fa-google-plus"></i>
                                </a>
                                <a  href="https://pinterest.com/pin/create/button/?url=" className="btn btn-social-icon btn-social-pinterest-p">
                                <i className="fa fa-pinterest-p"></i>
                                </a>
                            </div>
                          </div>
                      </div>
                    </div>
                </div>
              </div>
          </div>

    </div>
    <div className="more-from-brand-div">
          <a className="more-from-brand-link" href="#">More Like This</a>
        </div>
           <hr className="madal-hr-gray"/>
           <hr className="modal-hr-white"/>
        <div className="row product-listing-row-div" id="relatedProduct-data" dangerouslySetInnerHTML={{__html:this.state.morelikethis}}>

        </div>
    </div>
    </div>
    </div>
    :
    <App  {...this.props}/>
  }
   </div>
    );
  }
});

export default ProductDetails;`

Most helpful comment

@rickyn73 Can you post how you used parseFloat? I've attempted to do this and it still doesn't seem to be working...

All 5 comments

It should be you messed up the state. Try console log this:

center={this.state.center}
markers={this.state.markers}

in the first line of render(), and see if the data structure there is correct.

I have resolved this issue .This issue was due to Number format error so adding parseFloat to lat and lng works.

OK. Close for now

@rickyn73 Can you post how you used parseFloat? I've attempted to do this and it still doesn't seem to be working...

@njho sample to parse value

center: {
        lat: parseFloat('40.712784'),
        lng: parseFloat('-74.005941'),
      }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

MrSaints picture MrSaints  路  3Comments

tahir-masood1 picture tahir-masood1  路  4Comments

PaulieScanlon picture PaulieScanlon  路  3Comments

EvHaus picture EvHaus  路  3Comments

timkraut picture timkraut  路  3Comments