2014-10-02 188 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