为什么使用Google Places JavaScript客户端库会返回“NaN”,而API网址中的硬编码会返回准确的结果?

时间:2018-01-31 11:25:22

标签: javascript google-maps-api-3 google-places-api

我正在使用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客户端库运行类似的查询时,我得到了一个N​​aN。客户端库是否与可以查询的结果或我犯错误的Google Places API不相同?

//定义我的API密钥

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&amp;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;
    }

Screenshot/ Cannot embed as reputation too low

1 个答案:

答案 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;
}