如何在不使用div元素的情况下获得谷歌搜索服务?

时间:2016-04-28 21:54:40

标签: javascript google-maps google-api

我有这段代码:

<div id="map" style="display: none"></div>

JS

var map;
var infowindow;

function initMap() {
    var pyrmont = {lat: -36.1699, lng: 115.1398};

    map = new google.maps.Map(document.getElementById('map'));

    infowindow  = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.textSearch({
        location: pyrmont,
        radius  : 500,
        query   : 'Las Vegas Vehicle Inspection Stations'
    }, callback);
}

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

            console.log(results[i]);
        }
    }
}

要获得结果,我必须将map添加到var service = new google.maps.places.PlacesService(map);

有没有办法在不使用div元素的情况下获得结果?

任何想法?

1 个答案:

答案 0 :(得分:1)

您可以在没有地图 div的情况下获得结果。您需要提供google.maps.Map或HTML Div(因此可以呈现属性):

  

google.maps.places.PlacesService 构造函数

     

地方信息(attrContainer:HTMLDivElement |地图)
  创建PlacesService的新实例,该实例在指定容器中呈现属性。

proof of concept fiddle

代码段

function initMap() {
  var pyrmont = {
    lat: -36.1699,
    lng: 115.1398
  };
  var service = new google.maps.places.PlacesService(document.getElementById("placeDiv"));
  service.textSearch({
    location: pyrmont,
    radius: 500,
    query: 'Las Vegas Vehicle Inspection Stations'
  }, callback);
}

function callback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    var resultsStr = "<table><tr><th>name</th><th>coordinates</th></tr>";
    for (var i = 0; i < results.length; i++) {
      resultsStr += "<tr><td>" + results[i].name + "</td><td>" + results[i].geometry.location.toUrlValue(6) + "</td></tr>";
      console.log(results[i]);
    }
    resultsStr += "</table>";
    document.getElementById("results").innerHTML = resultsStr;
  }
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="placeDiv"></div>
<div id="results"></div>