如何使用反应来实现Google Place的搜索,在地图上创建标记?

问题描述 投票:1回答:1

我是React的新手,我创建了一个React项目。我想知道如何使用此默认入门项目来实现以下代码:code link from google。代码如下,链接到谷歌,上面。

Css file- 

/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}


HTML file-

<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>

Java script (pure js) file -

// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

var map;
var service;
var infowindow;

function initMap() {
  var sydney = new google.maps.LatLng(-33.867, 151.195);

  infowindow = new google.maps.InfoWindow();

  map = new google.maps.Map(
      document.getElementById('map'), {center: sydney, zoom: 15});

  var request = {
    query: 'Museum of Contemporary Art Australia',
    fields: ['name', 'geometry'],
  };

  service = new google.maps.places.PlacesService(map);

  service.findPlaceFromQuery(request, function(results, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]);
      }

      map.setCenter(results[0].geometry.location);
    }
  });
}

function createMarker(place) {
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(place.name);
    infowindow.open(map, this);
  });
}

我知道我需要使用Google Maps js和Google Places创建密钥,但是由于我是新人,所以我不确定如何将其实现到我的新React项目中。 Coudl有人向我展示了如何将这些代码文件放在一起以适合React工程。如果到处都是我,我深表歉意。

reactjs google-maps google-maps-markers google-places-api google-maps-react
1个回答
0
投票

您可以参考我提出的code。请记住更改“ YOUR_API_KEY”的值,以便地图可以正常工作。

这是App.js代码段:

import React from 'react';
import './App.css';
import Map from './components/placeSearch';

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

  handleMapLoad = (map) => {
    this.setState({
      map: map
    })
  }

  render() {
    return (
      <div className="App">
        <Map id="myMap" options={{center: { lat: 51.501904, lng: -0.115871 }, zoom: 13}}    onMapLoad = {this.handleMapLoad}/>  
      </div>

    );
  }
}

export default App;

用于位置搜索的代码可以在placeSearch.js的地图组件中找到。在此处更改您的API密钥的值。

import React from "react";
import ReactDOM from 'react-dom';

const map;
var markers = [];
var infowindow;
const API_KEY = "YOUR_API_KEY";
var place = [];


class Map extends React.Component {
    constructor(props) {
        super(props);
    }



    componentDidMount() {
            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.onScriptLoad()
            })

    }

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

        var request = {
            query: 'Museum of Contemporary Art Australia',
            fields: ['name', 'geometry'],
        };

        var service = new google.maps.places.PlacesService(map);

        service.findPlaceFromQuery(request, function(results, status) {
            if (status === google.maps.places.PlacesServiceStatus.OK) {
                for (var i = 0; i < results.length; i++) {

                    var place = results[i];
                    var marker = new google.maps.Marker({
                        map: map,
                        position:place.geometry.location,
                        title: place.formatted_address,
                    });
                    markers.push(marker);

                    infowindow = new google.maps.InfoWindow();

                    marker.addListener('click', () => {
                        infowindow.setContent(place.name);
                        infowindow.open(map, marker);
                    });
                }
                map.setCenter(results[0].geometry.location);
            }

        })
    }


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

        )
    }
}

export default Map;

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.