首页 > 解决方案 > reactjs中的谷歌地图

问题描述

我有一个代码,它根据缩放级别在右侧显示地图上的标记列表。例如:假设地图上总共有 5 个标记,如果我现在放大地图上只有 2 个标记,那么它只在右侧列出 2 个东西,如果我缩小然后假设有 3 个标记,那么 3 个东西是列出。因此,当我放大和缩小地图上的标记数量时,列表也会发生变化,但是该代码是用 javascript+jquery 编写的,但我正在研究 reactjs,而我只是 reactjs 的初学者。所以请帮我解决这个问题!

这就是代码的工作方式
如您所见,它列出了页面右侧的所有可见标记

这是代码.... HTML:

<h1>Google Maps - Visible Markers In Bounds</h1>

<div id="map-canvas"></div>

<div id="infos">
    <h2><span></span> visible beaches</h2>
    <div class="info info-1">Bondi Beach</div>
    <div class="info info-2">Coogee Beach</div>
    <div class="info info-3">Cronulla Beach</div>
    <div class="info info-4">Manly Beach</div>
    <div class="info info-5">Maroubra Beach</div>
</div>

<p>Try to zoom in/out.<br />Infos panels will be shown/hidden if markers visible on map.</p>

CSS:

#map-canvas {
    width:450px;
    height:340px;
}

#infos {
    position:absolute;
    top:60px;
    left:470px;
    width:300px;
}

#infos .info {
    background-color:#eee;
    padding:15px 25px;
    margin:10px 0;
}

p { 
    width:450px;
}

JS+JQUERY:

// Keep references
var map,
    markers = [];

// Our markers database (for testing)
var locations = [
    ['Bondi Beach', -33.890542, 151.274856],
    ['Coogee Beach', -33.923036, 151.259052],
    ['Cronulla Beach', -34.028249, 151.157507],
    ['Manly Beach', -33.80010128657071, 151.28747820854187],
    ['Maroubra Beach', -33.950198, 151.259302]
];


function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(-33.9, 151.2),
        zoom: 9,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };    
    
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    
    // Adding our markers from our "big database"
    addMarkers();
    
    // Fired when the map becomes idle after panning or zooming.
    google.maps.event.addListener(map, 'idle', function() {
        showVisibleMarkers();
    });
}

function addMarkers() {
    for (var i = 0; i < locations.length; i++) {
        var beach = locations[i],
            myLatLng = new google.maps.LatLng(beach[1], beach[2]),
            marker = new google.maps.Marker({
                position: myLatLng,
                title: beach[0]
            });         
        marker.setMap(map); 
        
        // Keep marker instances in a global array
        markers.push(marker);
    }
}

function showVisibleMarkers() {
    var bounds = map.getBounds(),
        count = 0;
                                   
    for (var i = 0; i < markers.length; i++) {
        var marker = markers[i],
            infoPanel = $('.info-' + (i+1) ); // array indexes start at zero, but not our class names :)
                                           
        if(bounds.contains(marker.getPosition())===true) {
            infoPanel.show();
            count++;
        }
        else {
            infoPanel.hide();
        }
    }
    
    $('#infos h2 span').html(count);
}

google.maps.event.addDomListener(window, 'load', initialize);

标签: javascriptjqueryreactjsgoogle-maps

解决方案


有一个没有。可用于加载 Maps JS API 的软件包/插件。但我建议动态加载它,而不是依赖于拥有自己的文档的 3rd 方库。这样,您就可以按照 Google 的官方地图文档进行操作。

这是一个示例供您参考:https ://stackblitz.com/edit/react-map-with-marker

应用程序.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import Map from './components/map';
import "./style.css";

class App extends Component {
 
  render() {
    return (
       <Map 
        id="myMap"
        options={{
          center: { lat: -33.8569, lng: 151.2152 },
          zoom: 8
        }}
      />
    );
  }
}

export default App;

样式.css

h1, p {
  font-family: Lato;
}

.map {
  height:500px;
  width:100%
}

地图.js

import React, { Component } from "react";
import { render } from "react-dom";

class Map extends Component {
  constructor(props) {
    super(props);
    this.state = {
      map: ""
    };
  }

  onScriptLoad() {
    this.state.map = new window.google.maps.Map(
      document.getElementById(this.props.id),
      this.props.options
    );

    var marker = new window.google.maps.Marker({
      position: { lat: -33.8569, lng: 151.2152 },
      map: this.state.map,
      title: "Hello Sydney!"
    });

    //adding markers by click
    this.state.map.addListener("click", e => {
      //Determine the location where the user has clicked.
      this.addMarker(e.latLng);
    });
  }

  componentDidMount() {
    if (!window.google) {
      var s = document.createElement("script");
      s.type = "text/javascript";
      s.src = `https://maps.google.com/maps/api/js?key=YOUR_API_KEY`;
      var x = document.getElementsByTagName("script")[0];
      x.parentNode.insertBefore(s, x);
      s.addEventListener("load", e => {
        this.onScriptLoad();
      });
    } else {
      this.onScriptLoad();
    }
  }

  addMarker(latLng) {
    var marker = new google.maps.Marker({
      position: latLng,
      map: this.state.map
    });
  }

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

export default Map;


推荐阅读