2014-09-25 2 views
0

나는 다음 스크립트가 있습니다jQuery를 구글지도 사용자 위치

 var directionDisplay; 
$(document).on("pageinit", "#calc", function() { 

    directionsDisplay = new google.maps.DirectionsRenderer(); 
    var defaultLatLng = new google.maps.LatLng(34.0983425, -118.3267434); // Default to Hollywood, CA when no geolocation support 
    if (navigator.geolocation) { 
     function success(pos) { 
      // Location found, show map with these coordinates 
      drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)); 
     } 
     function fail(error) { 
      drawMap(defaultLatLng); // Failed to find location, show default map 
     } 
     // Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds 
     navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000}); 
    } else { 
     drawMap(defaultLatLng); // No geolocation support, show default map 
    } 
    function drawMap(latlng) { 
     var myOptions = { 
      zoom: 10, 
      center: latlng, 
      mapTypeId: google.maps.MapTypeId.ROADMAP, 
      disableDefaultUI: true 
     }; 

     var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
     // Add an overlay to the map of current lat/lng 
     directionsDisplay.setMap(map); 
     var marker = new google.maps.Marker({ 
      position: latlng, 
      map: map, 
      title: "Greetings!" 

     }); 

    } 

}); 
var directionsService = new google.maps.DirectionsService(); 

function calcRoute() { 
    var start = document.getElementById("start").value; 
    var end = document.getElementById("end").value; 
    var request = { 
    origin:start, 
    destination:end, 
    travelMode: google.maps.DirectionsTravelMode.DRIVING 
    }; 

    directionsService.route(request, function(response, status) { 
    if (status == google.maps.DirectionsStatus.OK) { 
     directionsDisplay.setDirections(response); 
     var distanceInput = document.getElementById("distance"); 
     distanceInput.value = response.routes[0].legs[0].distance.value/1000; 

    } 
    }); 
} 

나는이 두 점 사이의 거리의의를 계산하려면를 최종 입력 값이됩니다 그리고 난 찾을 수 없습니다 시작은 을 사용자 gelocation 될 것입니다 그것을위한 온라인 솔루션. 길 찾기 서비스의 사용자 위치에 대한 Google API 구문은 무엇입니까? 나는 코드의

첫 번째 부분은 상당히 좋았다는 outpot는 km의

+0

먼저지도를 그리고 사용자 위치를 얻은 다음 geolocation 코드의 성공 콜백에'calcRoute'를 사용하십시오. 그렇게하면 사용자의 위치를 ​​전달할 수 있습니다. – Andy

+0

원점을 정의하는 방법 : LatLng? "LatLng undefined"오류가 발생합니다. –

+0

ive가 내 코드를 업데이트했습니다. –

답변

1

피르에있을 것입니다 필요가있다. 여기 예제에서 $(document).on("pageinit", "#calc", function() 대신 $(document).on("ready", function() ...을 사용했습니다. html 구조를 알지 못하기 때문에 시작합니다.

변경 사항 : calcRoute이 호출되면 Directions API에서 추가로 사용할 수있는 형식 인 latitude, longitude의 초기 위치가 저장됩니다. 테스트 그리고

function drawMap(latlng) { 
    var myOptions = { 
     zoom: 10, 
     center: latlng, 
     mapTypeId: google.maps.MapTypeId.ROADMAP, 
     disableDefaultUI: true 
    }; 

    // Log position in start input field 
    $("#start").val(latlng.k + ", " + latlng.B); 

    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
    // Add an overlay to the map of current lat/lng 
    directionsDisplay.setMap(map); 
    var marker = new google.maps.Marker({ 
     position: latlng, 
     map: map, 
     title: "Greetings!" 
    }); 
} 

, 내가 요구하는 버튼 calcRoute 추가 :

$("#calcBtn").click(function() { 
    calcRoute(); 
}); 

을 그리고 항상 응답을하고 무슨 일이 있었는지 알고 오류 처리를 추가 : 그것은 $("#start").val(latlng.k + ", " + latlng.B); 라인 아래가

directionsService.route(request, function(response, status) { 
    if (status == google.maps.DirectionsStatus.OK) { 
     directionsDisplay.setDirections(response); 
     var distanceInput = document.getElementById("distance"); 
     console.log(response); 
     distanceInput.value = response.routes[0].legs[0].distance.value/1000; 
    } else { 
     alert("Destination not found, error status: " + status); 
    } 
}); 

당신은 jsfiddle에서 테스트 할 수 있습니다 http://jsfiddle.net/gxjfnmdb/4/