2014-10-02 137 views
0

我試圖對地址進行地理編碼,在這種情況下Google HQ,然後使用places API在該地址附近找到機制。谷歌地圖渲染空白地圖

當我在我的網站把這個相同的代碼,在地圖呈現在片(見:https://stackoverflow.com/questions/26152702/map-created-with-google-maps-api-places-api-and-geocode-showing-map-with-ver?noredirect=1#comment41018580_26152702

然而,在JS小提琴(http://jsfiddle.net/ze1cpmt5/),它不會呈現在所有。與只在我的域中託管地圖的頁面相同。

實際上,代碼是不完全相同的,在JS小提琴中,它缺少我的密鑰,因爲使用密鑰,API會返回一條警告,聲明API已被阻止。此警報只發生在JSFiddle中的密鑰中。不在我的域名上。

這裏是我的代碼:

$.ajax({ 
    url: 'https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA', 
    dataType: 'json', 
    jsonp: 'callback', 
    method: 'GET', 
    success: function(results){ 
     console.log(results); 
     queryLat = results['results'][0]['geometry']['location']['lat']; 
     queryLong = results['results'][0]['geometry']['location']['lng']; 
     function callback(mapsResults, status){ 
      if(status == google.maps.places.PlacesServiceStatus.OK){ 
        for(var i=0; i<mapsResults.length; i++){ 
          var place = mapsResults[i]; 
          createMarker(mapsResults[i]); 
        } 
      } 
     } 
     var map; 
     var service; 
     map = new google.maps.Map(document.querySelector('body'), { 
      center:new google.maps.LatLng(queryLat, queryLong), 
      zoom:15 
     }); 
     var request = { 
      location: new google.maps.LatLng(queryLat, queryLong), 
      radius:'500', 
      query:'mechanic' 
     }; 
     service = new google.maps.places.PlacesService(map); 
     service.textSearch(request, callback); 
    } 
}); 

我將不勝感激,如果有人可以幫助我弄清楚,爲什麼它沒有呈現在爵士小提琴和我的域名的獨立頁面或爲什麼它被撕碎在我的整個網站。

+0

的[的jsfiddle](http://jsfiddle.net/ze1cpmt5/)具有JavaScript錯誤: '未捕獲的ReferenceError:未定義createMarker' – geocodezip 2014-10-02 20:55:14

+0

@geocodezip我在哪裏得到定義該函數的代碼?我在本文底部的代碼中查看文檔:https://developers.google.com/maps/documentation/javascript/places#place_search_requests它並沒有說要導入任何內容。 – wordSmith 2014-10-02 21:03:40

+2

您的查詢選擇器不會返回地圖的div以在[jsfiddle](http://jsfiddle.net/ncke0q7j/) – geocodezip 2014-10-02 21:10:18

回答

0

document.querySelector('body')不返回div。

使用代替一個div:

<div class="map" style="height:400px; width:400px;"></div> 

然後:

map = new google.maps.Map(document.querySelector('.map'), { 
    center: new google.maps.LatLng(queryLat, queryLong), 
    zoom: 15 
}); 

working fiddle

+0

這是爲什麼這樣工作? – 2017-03-04 18:44:57

+0

,因爲document.querySelector('body')沒有返回div,正如我的回答所說的那樣。您需要地圖的HTML Div元素。 – geocodezip 2017-03-04 19:02:03