2016-04-28 64 views
0

我有這樣的代碼:如何在不使用div元素的情況下獲得Google搜索服務?

<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]); 
     } 
    } 
} 

要得到的結果我必須添加mapvar service = new google.maps.places.PlacesService(map);

有沒有辦法得到的結果,而無需使用div元件?

有什麼想法嗎?

回答

1

你可以得到結果沒有地圖股利。您需要提供無論是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>

相關問題