[英]Why does using the Google Places JavaScript client library return “NaN”, while hardcoding in a API URL returns accurate results?
我正在使用Google的Places API,並且正在研究一個小型項目,該項目會根據用戶搜索的位置返回本地便利設施(學校,酒吧,餐廳,咖啡廳)的平均評分。 使用Google地方信息庫從HTML文件中的JavaScript查詢結果時,我發現正在返回NaN或“沒有任何數字”以獲取其他應有的評分,因為我知道該區域會有許多上面提到的設施。 某些地區會返回某家咖啡店和健身房的評分,而酒吧則為NaN,其他地區則為。 為了更深入地研究這個問題,我在瀏覽器中搜索了以下API URL,該URL以XML格式顯示了我希望用於特定區域的體育館的所有結果(以下屏幕截圖)。
https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=53.309362,-6.304930600000034&radius=1000&type=gym&key=MY_API_KEY
但是,當我通過Place的Javascript客戶端庫運行類似的查詢時,會得到NaN。 在可以查詢的結果方面,客戶端庫是否與Google Places API不相稱?或者我犯錯了嗎?
//定義我的API KEY
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>
//我如何查詢客戶端庫
function getGyms(){
//These are the laltitude and longitude values provided by the user
$('.search_latitude').val(marker.getPosition().lat());
$('.search_longitude').val(marker.getPosition().lng());
var Lat = marker.getPosition().lat();
console.log(Lat);
var Long = marker.getPosition().lng();
console.log(Long);
var gymLocation = {lat: Lat, lng: Long};
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: gymLocation,
radius: 2000,
type: ['gym']
}, gymCallback);
}
function gymCallback(results2, status2){
var totalRating = 0;
results2.forEach( function( place ) {
totalRating += place.rating;
});
//Calculating the average rating from the list of gyms
var averageRating = results2.length == 0 ? 0 : totalRating / results2.length;
var averageRatingRounded = averageRating.toFixed(1);
// Passing the rating to a TextBox
var averageGymRatingTB = document.getElementById('gymAvgRating');
averageGymRatingTB.value = averageRatingRounded;
}
api調用沒問題,問題在於如何處理代碼中的結果。
一些地方沒有評論,因此它們的評分是undefined
。
您的代碼還會嘗試在totalRating += place.rating;
添加這些undefined
評分totalRating += place.rating;
行,因此您會得到NaN
( 不是數字 )。
您可以忽略這些( 但在計算平均值時也要考慮在內 )
就像是
function gymCallback(results2, status2) {
var totalRating = 0,
ratedCount = 0; // used to count how many places have a rating
results2.forEach(function( place ) {
if (place.rating !== undefined) {
ratedCount++; // increase counter
totalRating += place.rating;
}
});
//Calculating the average rating from the list of gyms
var averageRating = results2.length == 0 ? 0 : totalRating / ratedCount; // use the counter to get the average since not all results were used for the totalRating
var averageRatingRounded = averageRating.toFixed(1);
// Passing the rating to a TextBox
var averageGymRatingTB = document.getElementById('gymAvgRating');
averageGymRatingTB.value = averageRatingRounded;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.