2017-07-25 217 views
0

我想在當前位置顯示附近的學校,但是,我不知道如何合併它們兩個,我爲獲取當前位置做了單獨的程序,但是現在我想要顯示當前位置周圍的附近位置。我做了一個fiddle。在這裏,我們給出了靜態經緯度,並且我希望它們成爲我當前位置的經緯度。所以這對我現在的位置,我可以看到附近的學校使用Google地圖在當前位置搜索附近的學校?

var pyrmont = {lat: -33.867, lng: 151.195}; 

回答

1

請試試這個碼。

在這裏您需要從腳本標記中刪除回調callback = initMap因此,它將如下所示。

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places" async defer></script> 

因爲首先我們要求的getLocation(),從地理位置獲得價值之後,我們手動調用initMap();

var temp_lat = ''; 
    var temp_lng = ''; 
    var map; 
    var infowindow; 
    getLocation(); 
    function getLocation() { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(showPosition); 
    } else { 
      temp_lat = 0.0; //set default lat value 
      temp_lng = 0.0; //set default lng value 
    } 
} 

function showPosition(position) { 
    temp_lat = position.coords.latitude; 
    temp_lng = position.coords.longitude; 
    initMap(); 
} 


function initMap() 
{ 
var pyrmont = {lat: temp_lat, lng: temp_lng}; 
map = new google.maps.Map(document.getElementById('map'), 
{ center: pyrmont, zoom: 15 }); 
infowindow = new google.maps.InfoWindow(); 
var service = new google.maps.places.PlacesService(map); service.nearbySearch(
{ location: pyrmont, radius: 500, type: ['school'] }, 
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); infowindow.open(map, this); }); } 

希望這會有所幫助。

+0

你是怎麼稱呼showposition func的? –

+0

使用此代碼。 navigator.geolocation.getCurrentPosition(showPosition);所以你只需要創建帶位置參數的showPosition函數(),這是谷歌地圖的默認功能。 –

+0

yar is fast:p –

相關問題