带有地理位置和地方搜索功能的Google Maps API

时间:2014-03-13 15:31:18

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

我正在使用Google地图并放置API。我正在尝试让地图显示当前位置与周围的餐馆,咖啡馆和酒吧。此时地图加载并且地理定位正在运行。我似乎无法让地方标记显示出来。因为我正在尽快学习javascript,所以我不知道自己错过了什么。

非常感谢任何帮助。谢谢!

这是我目前的代码:

<script>   
var map;
var service;
var marker;
var pos;
var infowindow;

function initialize() 
{

    var mapOptions = {
     zoom: 14,
     mapTypeId: google.maps.MapTypeId.ROADMAP,
     scrollwheel: false,
     panControl: false,
     streetViewControl: false,
     mapTypeControl: false,
     };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    //HTML5 geolocation
    if (navigator.geolocation) 
    {
       navigator.geolocation.getCurrentPosition(function(position) 
       {
            pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);

            infowindow = new google.maps.InfoWindow({map: map,position: pos,content: 'You Are Here'});

            var request = {location:pos,radius:500,types: ['restaurant, cafe, bars']};

            map.setCenter(pos);

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

        }, 

        function() 
        { 
        handleNoGeolocation(true);
        });
    } 
    else 
    {
    handleNoGeolocation(false);
    }

    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);
    infowindow.open(map, this);
    });

}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

2 个答案:

答案 0 :(得分:0)

检查您对Google API的脚本调用是否包含对地方库的引用。例如:

<script src="http://maps.googleapis.com/maps/api/js?key=yourAPIkey&libraries=geometry,places&sensor=true&language=en"></script>

答案 1 :(得分:0)

在这行代码中:

var request = {location:pos,radius:500,types: ['restaurant, cafe, bars']};

而不是types:keyword: