2017-11-17 15 views
-1

구글 맵스 API를 사용하여 3, 나는 클릭 이벤트와 폴리 라인을했습니다. 사용자가 클릭 한 경로의 두 지점을 알아야합니다. 포인트의 인덱스가 이상적입니다.구글 맵 폴리 라인 포인트 사이를 클릭하십시오

다음은 대부분 Google 문서에서 직접 가져온 샘플 페이지이지만 click 이벤트가 추가되었습니다. 실제 앱에는 훨씬 복잡한 폴리 라인이 있습니다.

이렇게하는 방법이 있습니까?

많은 감사

<!DOCTYPE html> 
<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"> 
<meta charset="utf-8"> 
<title>Polylines</title> 
<style>  
    #map { 
    height: 100%; 
    } 
    /* Optional: Makes the sample page fill the window. */ 
    html, body { 
    height: 100%; 
    margin: 0; 
    padding: 0; 
    } 
    </style> 
</head> 
<body> 
     <div id="map"></div> 
     <script> 
     function initMap() { 
      var map = new google.maps.Map(document.getElementById('map'), { 
      zoom: 3, 
      center: {lat: 0, lng: -180}, 
      mapTypeId: 'terrain' 
     }); 

     var flightPlanCoordinates = [ 
     {lat: 37.772, lng: -122.214}, 
     {lat: 21.291, lng: -157.821}, 
     {lat: -18.142, lng: 178.431}, 
     {lat: -27.467, lng: 153.027} 
     ]; 

     var poly = new google.maps.Polyline({ 
     path: flightPlanCoordinates, 
     geodesic: true, 
     strokeColor: '#FF0000', 
     strokeOpacity: 1.0, 
     strokeWeight: 2 
     }); 

     poly.setMap(map); 


     google.maps.event.addListener(poly, 'click', function(e) {    
     alert(JSON.stringify(e)); 
     }); 

    } 
</script> 
<script async defer 
src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initMap"> 
</script> 

답변

0

빠른 더러운 코드를 수행하면 최고가 될 수 없으며 기분이 언짢아 최적화 할 수 있습니다,하지만 난으로 올해부터 작업 그것.

내가 폴리 클릭 이벤트가이 코드 :

rc = getNearestVertex(poly, event.latLng); 
    x = rc.split(":"); //rc = "index:minDiff" 
    vertIndex = x[0] *1; 
    markerIndexes = vertIndex + ',' +(vertIndex + 1); 

내가 전에 점과 폴리 라인에 마커 후 지점을 표시하는 데 사용합니다. 함수 다음 :

function getNearestVertex(poly, pLatLng) { 
    // test to get nearest point on poly to the pLatLng point 
    // click is on poly, so the nearest vertex is the smallest diff between 
    var minDist = 9999999999; 
    var minDiff = 9999999999; 
    var path = poly.getPath(); 
    var count = path.length || 0; 

    for (var n = 0; n < count - 1; n++) { 
     if (n == 0) { 
      point = path.getAt(n); 
      dist = g.geometry.spherical.computeDistanceBetween(pLatLng, point); 
     } 
     //g.geometry.spherical.computeDistanceBetween(aLatLng, bLatLng) 
     var pointb = path.getAt(n + 1); 
     distb = g.geometry.spherical.computeDistanceBetween(pLatLng, pointb); 
     distp2p = g.geometry.spherical.computeDistanceBetween(point, pointb); 
     var pdiff = dist + distb - distp2p; 

     //alert(n + "/" +dist +" + " +distb +" - " +distp2p +" = " +pdiff); 
     if (pdiff < minDiff) { 
      minDiff = pdiff.toFixed(3); 
      index = n; 
     } 
     point = pointb; 
     dist = distb; 
    } //-> end for 
    //alert(index +":" + minDiff); 
    return index +":" + minDiff; 
} //-> end of getNearestVertex 

아마도 더 나은 js 및 수학을 가진 사람. 지식이 뛰어 들어 코드를 향상시킬 수 있습니다. 그러나 그것이 나를 위해 일하는 것에 따라, 나의 자전거 여행에 대한 나의 선로 - 점은 거의 2 - 3 - tsd 이상 드물지 않다. points

+0

나는이 길을 시작했지만, 컷백 도로가있을 때 문제가 발생합니다. "가장 가까운"지점은 경로상의 해당 지점에 실제로 있지 않은 도로에있을 수 있습니다. –

0

시도 :

poly.addListener('click', function() { 
     getPathVariableCode(poly); 
    }); 
poly.setMap(map); 

    function getPathVariableCode(line){ 
    var codeStr = ' var linePath = [\n'; 
    var pathArr = line.getPath(); 
    for (var i = 0; i < pathArr.length; i++){ 
     codeStr += ' {lat: ' + pathArr.getAt(i).lat() + ', lng: ' + pathArr.getAt(i).lng() + '}' ; 
     if (i !== pathArr.length-1) { 
      codeStr += ',\n'; 
     }; 

    }; 

    codeStr += '\n ];'; 

    //the coordinates path it´s print on the console of the browser 

    console.log (codeStr); 
    console.log(pathArr.length); 

}; 
+0

많은 감사합니다. 그러나 이것은 단지 경로를 출력합니다. 사용자가 점 0과 1 또는 2와 3 사이를 클릭했음을 알아야합니다. – pbs