谷歌地图渲染空白地图

Google Maps rendering blank map

本文关键字:地图 空白 谷歌地图      更新时间:2023-09-26

我正在尝试对地址进行地理编码,在本例中为Google HQ,然后使用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 fiddle(http://jsfiddle.net/ze1cpmt5/),它根本不渲染。我的域上只有地图的页面也是如此。

实际上代码并不完全相同,在JS Fiddle中,它缺少我的密钥,因为有了密钥,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);
    }
});

如果有人能帮我弄清楚为什么它没有在js fiddle和我域上的独立页面上呈现,或者为什么它在我的整个网站上呈现成碎片,我将不胜感激。

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

工作小提琴