2012-03-01 72 views
8

我試圖使用Google地方信息庫檢索地點詳細信息。當您單擊位置標記我希望能夠看到的地址,名稱,網站等Google Places API - 地點詳細信息請求undefined

我用下面的教程: http://code.google.com/apis/maps/documentation/javascript/places.html

所有看上去都不錯。在我的標記中,我可以顯示名稱和評分,但地址,網站和電話號碼都顯示爲「未定義」。這是因爲Google沒有我在這些地方要求的信息?或者我做錯了什麼?

下面是我正在使用的代碼: var map; var infowindow;

function initialize() { 
    var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316); 

    map = new google.maps.Map(document.getElementById('map_canvas'), { 
     mapTypeId: google.maps.MapTypeId.ROADMAP, 
     center: pyrmont, 
     zoom: 15 
    }); 

    var request = { 
     location: pyrmont, 
     radius: 5000, 
     types: ['bar'] 
    }; 
    infowindow = new google.maps.InfoWindow(); 
    service = new google.maps.places.PlacesService(map); 
    service.search(request, callback); 
    } 

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

    function createMarker(place) { 
    var placeLoc = place.geometry.location; 
    var marker = new google.maps.Marker({ 
     map: map, 
     position: place.geometry.location 
    }); 

    google.maps.event.addListener(marker, 'click', function() { 
     infowindow.setContent(place.name + "<br />" + place.formatted_address +"<br />" + place.website + "<br />" + place.rating + "<br />" + place.formatted_phone_number); 
     infowindow.open(map, this); 
    }); 
    } 

任何幫助或想法將不勝感激。

乾杯。

JA

回答

17

你做一個地方搜索,不返回所有字段的您正在使用的:

http://code.google.com/apis/maps/documentation/javascript/places.html#place_search_responses

爲了獲得地址,網站,你還需要撥打place.getDetails(),通過地方的reference。請參閱:

http://code.google.com/apis/maps/documentation/javascript/places.html#place_details_requests

粗略地說,你的代碼將變爲:

function createMarker(place) { 
    var placeLoc = place.geometry.location; 
    var marker = new google.maps.Marker({ 
     map: map, 
     position: place.geometry.location 
    }); 

    var request = { reference: place.reference }; 
    service.getDetails(request, function(details, status) { 
     google.maps.event.addListener(marker, 'click', function() { 
     infowindow.setContent(details.name + "<br />" + details.formatted_address +"<br />" + details.website + "<br />" + details.rating + "<br />" + details.formatted_phone_number); 
     infowindow.open(map, this); 
     }); 
    }); 
    } 
+0

就是這樣。非常感謝。我非常感謝你的幫助。 – Jim 2012-03-01 22:37:44

+0

沒問題!很高興我能幫助:) – 2012-03-02 00:23:24

+0

嗨..我面臨着同樣的問題,並嘗試過這種解決方案。但無法獲得結果。「service.getDetails(request,function(details,status)」在哪裏聲明這個服務變量?我需要在create marker函數中再次聲明這個嗎? – Thakur 2017-11-23 07:15:35

相關問題