如何使用 React 和 Google Places API 在 Google 地图上显示地点标记?

     2023-02-23     256

关键词:

【中文标题】如何使用 React 和 Google Places API 在 Google 地图上显示地点标记?【英文标题】:How can I use React with Google Places API, to display place markers on a Google map? 【发布时间】:2018-04-17 06:31:10 【问题描述】:

我正在尝试构建与on Airbnb 类似的地图,您可以在其中拖动地图时查看地点标记。 我想在地图上显示来自 Google Places API 的“酒店”标记。

使用 Google Maps 中的以下 JavaScript 代码,我可以在 Google 地图上显示酒店,但我想使用 React 来做到这一点,使用 react-google-maps。

<!DOCTYPE html>
<html>
  <head>
    <title>Place searches</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* 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;
      
    </style>
    <script>
      // 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 infowindow;

      function initMap() 
        var pyrmont = lat: -33.867, lng: 151.195;

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

        infowindow = new google.maps.InfoWindow();
        var service = new google.maps.places.PlacesService(map);
        service.nearbySearch(
          location: pyrmont,
          radius: 500,
          type: ['hotel']
        , callback);
      

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

      function createMarker(place) 
        var placeLoc = place.geometry.location;
        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);
        );
      
    </script>
  </head>
  <body>
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>
  </body>
</html>

react-google-maps 有一个显示搜索输入字段的示例。因此,我可以通过搜索来搜索和显示标记,例如“伦敦的酒店”。但是,我不想搜索地点,而是想立即显示酒店的标记。 (以下示例中的 API 密钥来自 react-google-maps 示例。)

const _ = require("lodash");
const  compose, withProps, lifecycle  = require("recompose");
const 
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
 = require("react-google-maps");
const  SearchBox  = require("react-google-maps/lib/components/places/SearchBox");

const MapWithASearchBox = compose(
  withProps(
    googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style= height: `100%`  />,
    containerElement: <div style= height: `400px`  />,
    mapElement: <div style= height: `100%`  />,
  ),
  lifecycle(
    componentWillMount() 
      const refs = 

      this.setState(
        bounds: null,
        center: 
          lat: 41.9, lng: -87.624
        ,
        markers: [],
        onMapMounted: ref => 
          refs.map = ref;
        ,
        onBoundsChanged: () => 
          this.setState(
            bounds: refs.map.getBounds(),
            center: refs.map.getCenter(),
          )
        ,
        onSearchBoxMounted: ref => 
          refs.searchBox = ref;
        ,
        onPlacesChanged: () => 
          const places = refs.searchBox.getPlaces();
          const bounds = new google.maps.LatLngBounds();

          places.forEach(place => 
            if (place.geometry.viewport) 
              bounds.union(place.geometry.viewport)
             else 
              bounds.extend(place.geometry.location)
            
          );
          const nextMarkers = places.map(place => (
            position: place.geometry.location,
          ));
          const nextCenter = _.get(nextMarkers, '0.position', this.state.center);

          this.setState(
            center: nextCenter,
            markers: nextMarkers,
          );
          // refs.map.fitBounds(bounds);
        ,
      )
    ,
  ),
  withScriptjs,
  withGoogleMap
)(props =>
  <GoogleMap
    ref=props.onMapMounted
    defaultZoom=15
    center=props.center
    onBoundsChanged=props.onBoundsChanged
  >
    <SearchBox
      ref=props.onSearchBoxMounted
      bounds=props.bounds
      controlPosition=google.maps.ControlPosition.TOP_LEFT
      onPlacesChanged=props.onPlacesChanged
    >
      <input
        type="text"
        placeholder="Customized your placeholder"
        style=
          boxSizing: `border-box`,
          border: `1px solid transparent`,
          width: `240px`,
          height: `32px`,
          marginTop: `27px`,
          padding: `0 12px`,
          borderRadius: `3px`,
          boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
          fontSize: `14px`,
          outline: `none`,
          textOverflow: `ellipses`,
        
      />
    </SearchBox>
    props.markers.map((marker, index) =>
      <Marker key=index position=marker.position />
    )
  </GoogleMap>
);

<MapWithASearchBox />

我已经尝试解决这个问题很多天了,并且一直在寻找教程,但我找不到解决方案。我明白我应该使用:

new google.maps.places.PlacesService()

并添加选项:

 const center = new google.maps.LatLng(37.422, -122.084068);
 const options = 
   location: center
   radius: '500',
   types: ['hotel']
 ;

当使用 react-google-maps 时,我需要使用 withScriptjs。但是我该如何把所有这些放在一起呢?

如何使用 react-google-maps 和 Google Places API,在地图上显示来自 Google 的“酒店”标记?

【问题讨论】:

【参考方案1】:

您可以通过将GoogleMap 的引用传递给new google.maps.places.PlacesService() 来创建服务,然后使用该服务,您可以使用nearbySearch() 搜索酒店、餐馆等。正如Google Places Nearby Search API docs 所说:

“附近搜索”可让您按关键字或类型搜索指定区域内的地点。

要触发fetchPlaces() 方法,您可以使用GoogleMap 组件或componentDidMount() 中的onTilesLoaded 属性。在下面的示例中,我还将fetchPlaces 传递给onBoundChanged,因为我的搜索基于bounds,因此每次移动地图时它都可以为我提供新的地点,请注意:

const bounds = refs.map.getBounds();
const service = new google.maps.places.PlacesService(refs.map.context.__SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED);
const request = 
  bounds: bounds,
  type: ['hotel']
;

这是我使用 recompose 的示例:

/*global google*/
import React from "react"
import  compose, withProps, withHandlers, withState  from "recompose"
import  withScriptjs, withGoogleMap, GoogleMap, Marker  from "react-google-maps"

const MyMapComponent = compose(
    withProps(
        googleMapURL: "https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places",
        loadingElement: <div style= height: `100%`  />,
        containerElement: <div style= height: `400px`  />,
        mapElement: <div style= height: `100%`  />,
    ),
    withScriptjs,
    withGoogleMap,
    withState('places', 'updatePlaces', ''),
    withHandlers(() => 
        const refs = 
            map: undefined,
        

        return 
            onMapMounted: () => ref => 
                refs.map = ref
            ,
            fetchPlaces: ( updatePlaces ) => 
                let places;
                const bounds = refs.map.getBounds();
                const service = new google.maps.places.PlacesService(refs.map.context.__SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED);
                const request = 
                    bounds: bounds,
                    type: ['hotel']
                ;
                service.nearbySearch(request, (results, status) => 
                    if (status == google.maps.places.PlacesServiceStatus.OK) 
                        console.log(results);
                        updatePlaces(results);
                    
                )
            
        
    ),
)((props) => 
    return (
        <GoogleMap
            onTilesLoaded=props.fetchPlaces
            ref=props.onMapMounted
            onBoundsChanged=props.fetchPlaces
            defaultZoom=8
            defaultCenter= lat: 51.508530, lng: -0.076132 
        >
            props.places && props.places.map((place, i) =>
                <Marker key=i position= lat: place.geometry.location.lat(), lng: place.geometry.location.lng()  />
            )
        </GoogleMap>
    )
)

export default class MyFancyComponent extends React.PureComponent 
    render() 
        return (
            <MyMapComponent />
        )
    

【讨论】:

Tiago,我还有一个相关的问题,你可能知道答案吗? :) ***.com/questions/47205165/…

如何使用 React、Redux 和 Webpack 实现 Google API

】如何使用React、Redux和Webpack实现GoogleAPI【英文标题】:HowtoimplementGoogleAPIwithReact,ReduxandWebpack【发布时间】:2017-09-2813:22:51【问题描述】:我正在尝试将Google日历事件添加到我的ReactRedux应用程序中。我尝试使用googleapis和google-auth... 查看详情

如何使用 React 和 Google Places API 在 Google 地图上显示地点标记?

】如何使用React和GooglePlacesAPI在Google地图上显示地点标记?【英文标题】:HowcanIuseReactwithGooglePlacesAPI,todisplayplacemarkersonaGooglemap?【发布时间】:2018-04-1706:31:10【问题描述】:我正在尝试构建与onAirbnb类似的地图,您可以在其中拖... 查看详情

优化以使用 react-google-maps 进行标记

】优化以使用react-google-maps进行标记【英文标题】:optimizetomarkwithreact-google-maps【发布时间】:2018-08-0517:33:32【问题描述】:我目前正在使用react-google-maps开发GoogleMap页面。我的代码如下classGoogleMapBoxextendsReact.Componentstate=center:this.... 查看详情

如何使用 axios 为 Google 地图和 React 中的 placeid 获取数据?

】如何使用axios为Google地图和React中的placeid获取数据?【英文标题】:HowtofetchdatawithaxiosforaplaceidinGooglemapsandReact?【发布时间】:2018-11-1919:53:59【问题描述】:我有一个状态为restaurantsFetchedFromGoogle的数组,它当前存储了以前从谷... 查看详情

如何在 React.js 中使用 Google 字体?

】如何在React.js中使用Google字体?【英文标题】:HowtouseGooglefontsinReact.js?【发布时间】:2017-04-0718:18:38【问题描述】:我用React.js和webpack建立了一个网站。我想在网页中使用Google字体,所以我把链接放在了这个部分。GoogleFonts<l... 查看详情

我使用 Google place Api,但是当在银行和餐厅等搜索地点附近使用时……这行不通?

】我使用GoogleplaceApi,但是当在银行和餐厅等搜索地点附近使用时……这行不通?【英文标题】:iuseGoogleplaceApibutwhenusenearsearchplacelikebank&restaurant&..thisnotwork?【发布时间】:2016-01-2002:38:33【问题描述】:1.i为android启用androidg... 查看详情

如何触发 best_in_place 事件

】如何触发best_in_place事件【英文标题】:Howtotriggerbest_in_placeevents【发布时间】:2014-04-1410:15:15【问题描述】:我查看了所有的Google和***,并查看了best_in_placejavascript代码,但无济于事。我正在使用best_in_place通过使用textarea来编... 查看详情

如何在 react-google-maps 中添加标记?

】如何在react-google-maps中添加标记?【英文标题】:Howtoaddmarkersinreact-google-maps?【发布时间】:2017-11-1702:04:45【问题描述】:在Meteor1.5中使用ReactJS问题:需要一种方法来添加Marker使用react-google-maps使用ES6和JSX格式遵循文档并能够... 查看详情

如何使用 react-google-maps 显示多个标记

】如何使用react-google-maps显示多个标记【英文标题】:HowdoIdisplaymultiplemarkerswithreact-google-maps【发布时间】:2017-10-0704:08:31【问题描述】:我正在尝试使用名为react-google-maps的npm包显示多个标记,但我遇到了困难。我在此处关注如... 查看详情

Google Place API 葡萄牙语

...uguese【发布时间】:2016-01-1518:21:52【问题描述】:我正在使用Google的PlaceAPI来自动完成用户输入的城市名称(网页)。加载API时将语言(pt-BR)作为参数传递,并且文本框以葡萄牙语正确填写,但是当方法getPlace()执行时,它会以英... 查看详情

如何在 Google Place AutocompleteViewController 的 GMSAutocompleteViewController 中设置文本

】如何在GooglePlaceAutocompleteViewController的GMSAutocompleteViewController中设置文本【英文标题】:HowtosettextinGMSAutocompleteViewControllerinGooglePlaceAutocompleteViewController【发布时间】:2017-05-1320:51:36【问题描述】:在我的应用程序中打开时,我... 查看详情

使用 Google Place API 获取事件

】使用GooglePlaceAPI获取事件【英文标题】:UsingGooglePlaceAPItogetevents【发布时间】:2014-05-3120:55:47【问题描述】:我正在尝试使用PlaceAPI获取当前附近的事件。我目前正在关注这个tutorial,但我无法在返回的JSON对象中获取事件数组... 查看详情

使用 Google Place API 自动完成 TextView

】使用GooglePlaceAPI自动完成TextView【英文标题】:AutocompleteTextViewusingGooglePlaceAPI【发布时间】:2015-07-2809:03:46【问题描述】:尝试使用GooglePlaceAPI开发AndroidAutoCompleteTextView,当我在浏览器中尝试我的编码URL时遇到一个奇怪的错误。... 查看详情

如何使用 react-google-maps 库创建折线

】如何使用react-google-maps库创建折线【英文标题】:HowtocreatePolylineusingreact-google-mapslibrary【发布时间】:2018-01-0717:15:46【问题描述】:我正在尝试使用react-google-maps库在4个GPS坐标之间绘制折线。地图上没有渲染任何内容importReactfr... 查看详情

Google Places Autocomplete - 如何获取纬度和经度?

】GooglePlacesAutocomplete-如何获取纬度和经度?【英文标题】:GooglePlacesAutocomplete-howtogetLatitudeandLongitude?【发布时间】:2015-02-2615:26:31【问题描述】:我使用网址:https://maps.googleapis.com/maps/api/place/autocomplete/json?input=bar&key=API_KE 查看详情

适用于 Android 的 Google Place API:无法使用 Place Picker 的选择器选择地点

】适用于Android的GooglePlaceAPI:无法使用PlacePicker的选择器选择地点【英文标题】:GooglePlaceAPIforAndroid:can\'tselectplacewiththepickerofPlacePicker【发布时间】:2016-11-1613:35:56【问题描述】:我添加到我的android应用程序PlacePicker。当您知道... 查看详情

如何通过google javascript api获取知道place_id的位置坐标

】如何通过googlejavascriptapi获取知道place_id的位置坐标【英文标题】:Howtogetlocationcoordinatesknowingplace_idviagooglejavascriptapi【发布时间】:2015-06-2123:20:17【问题描述】:我知道place_id,我需要知道它的坐标。我可以GEThttps://maps.googleapis.... 查看详情

我从 react native 开始,如何正确安装 yarn?已经尝试过 google 和 YouTube

】我从reactnative开始,如何正确安装yarn?已经尝试过google和YouTube【英文标题】:Iamstartingoutinreactnative,howdoIinstallyarncorrectly?AlreadytriedgoogleandYouTube【发布时间】:2021-04-2507:32:33【问题描述】:这是我的第一篇文章。我刚刚开始使用... 查看详情