我正在使用Google的Places API并开发一个迷你项目,该项目根据用户搜索的位置返回当地设施(学校,酒吧,餐厅,咖啡馆)的平均评分。使用Google商家信息库查询HTML文件中JavaScript的结果,我发现NaN或非任何数字正在返回评级,否则应该在那里,因为我知道该区域将有一些上面提到的设施。一些地区将返回评级,让我们说咖啡馆,健身房,但NaN为酒吧,反之亦然其他地区。为了更深入地研究这个问题,我在我的浏览器中搜索了以下API 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密钥
<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;
}
答案 0 :(得分:2)
api调用没有问题,问题在于如何处理代码中的结果。
有些地方没有评论,因此评分为undefined
。
您的代码会尝试在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;
}