如何使用fitbounds()来居中并显示反应中的所有标记

时间:2018-03-20 20:03:39

标签: reactjs google-maps-react

我是一个有反应的初学者,我正在尝试使用circle()和fitbounds()来让我的所有标记显示在屏幕上。现在只有第一个标记显示在屏幕上,但当我缩小时,我可以看到其余的。但是,我希望在运行应用程序时显示所有标记。帮助会很棒! 我尝试使用/ 全局谷歌 /然后声明存储google.maps.latLngBounds()的const界限,但它给了我一个引用错误,说谷歌没有定义。我创建了一个带有谷歌窗口的const,但错误仍然存​​在。由于我不太了解反应,我不知道我哪里出错了。

此外,代码段需要在我删除API密钥时运行网址中的API_KEY。

/*global google*/
//Declaring the imports

import React, { Component } from 'react';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react- 
google-maps";`enter code here`
import { Circle } from "react-google-maps";

//The bounds give me a google not defined error 
//const google = window.google;
//const bounds = new google.maps.LatLngBounds();



const MyMapComponent = withScriptjs(withGoogleMap((props) =>

//Creating the GoogleMap instance tag that takes a default zoom and uses only one center
<GoogleMap
    defaultZoom={13}
    center={{ lat: 35.8592, lng: -78.5921 }}
>
    {}
    {props.isMarkerShown &&
        props.markers.map((marker, index) => {

               //MarkerOptions
                return (
                    <Marker
                        position={marker}
                        title="Click to zoom"
                        label={"" + ((index + 1))}
                        onClick={props.onMarkerClick}
                    />
                )
        })
    }
</GoogleMap>
))


const numbers = [1, 2, 3, 4, 5];

const listItems = numbers.map((number) =>
    <li>{number}</li>
)

//The three markers being placed
const storeLocations = [
 { "lat": 35.8592, "lng": -78.5921 },
 { "lat": 35.8964, "lng": -78.5734 },
 { "lat": 35.8794, "lng": -78.5693 }
]

export default class MapComponent extends Component {

state = {
    isMarkerShown: false,
    selectedMarkerNumber: 0
}

componentDidMount() {
    this.setState({ isMarkerShown: true })
}

delayedShowMarker = () => {
    setTimeout(() => {
        this.setState({ isMarkerShown: true })
    }, 3000)
}

animatePin() {

    const min = 1;
    const max = 4;
    const rand = min + Math.floor(Math.random() * (max - min));
    console.log("rand" + rand)

    this.setState({
        selectedMarkerNumber: rand
    })
}

//Render function
render() {
    return (
        <div>
            <MyMapComponent
                isMarkerShown={this.state.isMarkerShown}
                googleMapURL="https://maps.googleapis.com/maps/api/js?key=<API_KEY>&v=3.exp&libraries=geometry,drawing,places"
                loadingElement={<div style={{ height: `100%` }} />}
                containerElement={<div style={{ height: `250px` }} />}
                mapElement={<div style={{ height: `100%` }} />}
                onMarkerClick={this.handleMarkerClick}
                markers={storeLocations}
            />
            <div className="item" color="green" onClick={() => this.animatePin()}>
                <ul>{listItems}</ul>
            </div>
        </div>
        )

    }

}

0 个答案:

没有答案