【问题标题】:Google Map Integration with React Js projects谷歌地图与 React Js 项目的集成
【发布时间】:2020-08-30 07:27:15
【问题描述】:

需要使用 Google Maps API 来获得所需的输出:{'hotels','atms','banks','hospitals'}.

已经尝试过google-map-react,但不能正常工作。

要求可以是以下任意一种:

  • 免费接口
  • 脚本
  • 图书馆。

参考图片:

【问题讨论】:

    标签: javascript reactjs google-maps google-maps-api-3


    【解决方案1】:

    您可以使用Google Maps Javascript's Places Nearby Search 使用您提到的不同关键字搜索附近的地方。这是来自 Google 地图文档的sample code

    您也可以使用下面的代码 sn-p 在 reactjs 中实现它,并具有与您的用例类似的功能。

    import React from "react";
    import ReactDOM from "react-dom";
    import "./style.css";
    
    let map;
    const API_KEY = "YOUR_API_KEY";
    const coords = { lat: 41.375885, lng: 2.177813 };
    let markers = [];
    
    class NearbySearchApp extends React.Component {
      constructor(props) {
        super(props);
        this.renderMap = this.renderMap.bind(this);
        this.handleClick = this.handleClick.bind(this);
      }
    
      componentDidMount() {
        if (!window.google) {
          const script = document.createElement("script");
          script.type = "text/javascript";
          script.src =
            `https://maps.googleapis.com/maps/api/js?key=` +
            API_KEY +
            `&libraries=geometry,places`;
          script.id = "googleMaps";
          script.async = true;
          script.defer = true;
          document.body.appendChild(script);
          script.addEventListener("load", (e) => {
            this.renderMap();
          });
        } else {
          this.renderMap();
        }
      }
    
      renderMap() {
        const el = document.getElementById("map");
    
        if (el) {
          map = new google.maps.Map(el, {
            zoom: 14,
            center: {
              lat: coords.lat,
              lng: coords.lng,
            },
          });
    
          return map;
        } else {
          return null;
        }
      }
    
      handleClick(data) {
        //clearing markers and marker array everytime a keyword is clicked
        for (let i = 0; i < markers.length; i++) {
          markers[i].setMap(null);
        }
        markers = [];
    
    
        document.getElementById("chosen").innerHTML =
          "You clicked: " + data.keyword;
    
        //NearbySearch function  
        let service = new google.maps.places.PlacesService(map);
        service.nearbySearch(
          { location: coords, radius: 500, type: [data.keyword] },
          function (results, status, pagination) {
            if (status !== "OK") return;
            const bounds = new google.maps.LatLngBounds();
            for (let i = 0, place; (place = results[i]); i++) {
              //creating markers icon per type of place
              let image = {
                url: place.icon,
                size: new google.maps.Size(71, 71),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(17, 34),
                scaledSize: new google.maps.Size(25, 25),
              };
              //creates marker for every place result
              const marker = new google.maps.Marker({
                map: map,
                icon: image,
                title: place.name,
                position: place.geometry.location,
              });
              //putting markers in the array
              markers.push(marker);
              //showing markers from the array in the map
              for (let i = 0; i < markers.length; i++) {
                markers[i].setMap(map);
              }
    
              bounds.extend(place.geometry.location);
            }
          }
        );
      }
    
      render() {
        return (
          <section>
            <h1>ADD YOUR API KEY TO MAKE IT WORK</h1>
    
            <div id="map" />
            <div id="panel">
              <h3 id="chosen">Please choose a Place:</h3>
              <input
                type="button"
                onClick={this.handleClick.bind(null, { keyword: "atm" })}
                value="ATM"
              /><br/>
              <input
                type="button"
                onClick={this.handleClick.bind(null, { keyword: "hospital" })}
                value="Hospital"
              /><br/>
              <input
                type="button"
                onClick={this.handleClick.bind(null, { keyword: "store" })}
                value="store"
              />
            </div>
          </section>
        );
      }
    }
    
    export default NearbySearchApp;
    

    您可以使用export default 导出 NearbySearchApp 并将其导入另一个脚本文件,如下所示:

    
    import React from 'react';
    import ReactDOM from 'react-dom';
    import NearbySearchApp from './NearbySearchApp';
    
    ReactDOM.render(<NearbySearchApp />, document.getElementById('app'));
    
    

    这是一个实现此功能的sample code。确保使用您的 API 密钥以使示例代码正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      相关资源
      最近更新 更多