2017-12-04 2 views
-1
function getCoords(position) 
{ 
    var longitude = position.coords.latitude; 
    var latitude = position.coords.longitude; 
    var coords = new google.maps.LatLng(latitude, longitude); 
    alert(coords); 
    }); 
} 

초기화 기능에 위도 LNG를 통과 할 수 없습니다이 내가 변수 <code>coords</code> 처음 필요한 초기화 기능입니다

function initMap() 
{ 
    map = new google.maps.Map(document.getElementById('map'), { 
     center: {lat: 22.5726, lng: 88.3639}, 
     zoom: 13 
    }); 

    infoWindow = new google.maps.InfoWindow; 

    // Try HTML5 geolocation. 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(function(position) 
     { 
      var marker = new google.maps.Marker({ 
       position: coords, 
       map: map, 
       title: "You're here Bro!", 
       draggable: true, 
       animation: google.maps.Animation.DROP, 
      }); 

      infoWindow.setPosition(coords); 
      infoWindow.setContent("You're here Bro!"); 

      infoWindow.open(map , marker); 
      map.setCenter(coords); 
     }, function() { 
      handleLocationError(true, infoWindow, map.getCenter()); 
     }); 
    } else { 
     // Browser doesn't support Geolocation 
     handleLocationError(false, infoWindow, map.getCenter()); 
    } 

    new AutocompleteDirectionsHandler(map); 
} 

이 내가 변수 coords초 시간을 필요로하는 초기화 함수를

AutocompleteDirectionsHandler.prototype.route = function() { 
    if (!this.destinationPlaceId) { 
     return; 
    } 

    var me = this; 

    this.directionsService.route({ 
     origin: coords, 
     destination: {'placeId': this.destinationPlaceId}, 
     travelMode: this.travelMode 
    }, function(response, status) { 
     if (status === 'OK') { 
      me.directionsDisplay.setDirections(response); 
     } else { 
      window.alert('Directions request failed due to ' + status); 
     } 
    }); 
}; 

이 코드는 coords 변수를 함수로 전달할 수 없습니다. 첫 번째 기능은지도 시작을위한 것이고 하나는 경로를위한 것입니다.

답변

0

'coords'변수에 다른 범위로 액세스하려고합니다. 어쩌면 getCoords 함수 밖에서 선언하려고 시도하고 getCoords 안에 설정하십시오. 다음과 같이하십시오 :

var coords = null; 
function getCoords(position) 
{ 
var longitude = position.coords.latitude; 
var latitude = position.coords.longitude; 
coords = new google.maps.LatLng(latitude, longitude); 
alert(coords); 
}); 
} 
+0

일어나지 않습니다. 마커가없고 정보창이 다른 위치에 있습니다. –

+0

'initMap' 함수에서 새로운 마커를 만들 때'position : coords'를'position : {lat : position.coords.latitude, lng : position.coords.longitude}'로 대체하십시오. –