2014-10-26 71 views
0

這是我的第一個HTML/Javascript項目,我遇到了一些麻煩。我們的目標是獲得一個地址,並在該地址500米內的商店上簡單地顯示帶有標記的地圖。問題是我得到一個空白頁面;什麼也沒有顯示出來。這些代碼大部分都是從谷歌的例子中逐字複製的,所以我不知道什麼是錯的。地圖不顯示在網頁上(谷歌地圖/ Places API)

HTML:

<!DOCTYPE html> 
<html> 
    <head> 
    <title>Make a Good Impression</title> 
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=myKeyGoesHere"></script>  
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script> 
    <script type="text/javascript" src="coffee_and_donuts.js"></script> 
    </head> 
    <body> 
     <div id="map" style="float:left;width:30%;height 100%"></div> 
    </body> 
</html> 

coffee_and_donuts.js:

var directionsDisplay; 
var directionsService = new google.maps.DirectionsService(); 
var geocoder = new google.maps.Geocoder(); 
var DESTINATION_ADDRESS = "New York, New York"; 
var destination_LatLng; 


// get the destination's LatLng object 
geocoder.geocode({'address': DESTINATION_ADDRESS}, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) 
    { 
     destination_LatLng = results[0].geometry.location; 
    } 
}); 


// feed the destination's LatLng object to the places API to find the nearest stores 

var map; 
var service; 
var infowindow; 

function initialize2() { 
    map = new google.maps.Map(document.getElementById('map'), { 
     center: destination_LatLng, 
     zoom: 15 
    }); 

    var request = { 
    location: destination_LatLng, 
    radius: '500', 
    types: ['store'] 
    }; 

    service = new google.maps.places.PlacesService(map); 
    service.nearbySearch(request, callback); 
} 

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

initialize2(); 
+0

做一個小提琴,我可以幫忙 – 2014-10-26 23:50:28

+0

我不知道這個工具。很酷。 http://jsfiddle.net/8hga1h52/ – JamesGold 2014-10-26 23:53:12

+0

插入你的API密鑰 – 2014-10-26 23:54:05

回答

1

你需要調用initialize2();從您的地址解析函數回調中:

// get the destination's LatLng object 
    geocoder.geocode({'address': DESTINATION_ADDRESS}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) 
     { 
      destination_LatLng = results[0].geometry.location; 
      initialize2(); 
     } 
    }); 

的問題是,你試圖在地理編碼器完成之前初始化地圖。

你也可以把所有這一切在一個鏈接:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script> 
+0

謝謝,這是有道理的。雖然地圖仍然沒有渲染。 – JamesGold 2014-10-27 00:23:49

+0

你也不能使用浮動div的100%高度,除非你給它的容器增加一個高度,把它設置爲600px或者其他東西,它應該顯示 – 2014-10-27 00:25:12

+0

它就是這樣。謝謝! – JamesGold 2014-10-27 00:26:51