点击它时突出显示折线路线 - Google Maps v3

时间:2014-08-09 13:46:41

标签: routes highlight polyline

我的地图上有很多路线,我想在点击它时突出显示一条路线。 在这里我附上我的代码,请检查它并建议我解决方案,以高亮显示地图上点击的路线。

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places,geometry" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/directions/output?alternatives=true"></script>
</head>
<body>
<style>
body {
  font-size: 0.8em;
}
#map 
{
    width: 750px;
    height: 600px;
    margin-top: 10px;
}
#map-container, #side-container, #side-container li {
  float: left;
}

#map-container {
  width: 750px;
  height: 600px;
}
#side-container {
  border: 1px solid #bbb;
  margin-right: 5px;
  padding: 2px 4px;
  text-align: right;
  width: 260px;
}
#side-container ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
#side-container li input {
  font-size: 0.85em;
  width: 210px;
}
#side-container .dir-label {
  font-weight: bold;
  padding-right: 3px;
  text-align: right;
  width: 40px;
}
#dir-container {
  height: 525px;
  overflow: auto;
  padding: 2px 4px 2px 0;
}
#dir-container table {
  font-size: 1em;
  width: 100%;
}
</style>
<body>
    <div id="side-container">
    <form id="calculate-route" name="calculate-route" action="#" method="get">
      <ul>
        <li class="dir-label">From:</li>
        <li><input type="text" id="searchTextFieldSource" name="searchTextFieldSource" autocomplete="on" value="New York, NY, United States" placeholder="Enter Source"/></li>
        <br clear="both"/>
        <li class="dir-label">To:</li>
        <li><input type="text" id="searchTextFieldDestination" name="searchTextFieldDestination" autocomplete="on" value="California, United States" placeholder="Enter Destination"/></li>
      </ul>
    <div>
    <select onChange="Demo.getDirections();" id="travel-mode-input">
      <option value="driving" selected="selected">By car</option>
      <option value="bicycling">Bicycling</option>
      <option value="walking">Walking</option>
      <option value="driving">Driving</option>
    </select>
    <select onChange="Demo.getDirections();" id="unit-input">
      <option value="imperial" selected="selected">Imperial</option>
      <option value="metric">Metric</option>
    </select>
    <input type="checkbox" name="routes_option" id="routes_option"/>Multiple Routes
    <input type="submit" id="submit" name="submit" onClick="Demo.getDirections();"  value="Go!"/>
</form>
  </div>
  <!--<div id="map"></div>-->
<div id="dir-container"></div>
</div>
<div id="map"></div>
 <p id="error"></p>
<script type="text/javascript">
            var locations = new Array();
            var directionsDisplay;
            var directionsService = new google.maps.DirectionsService();

            //calculates distance between two points in km's
            function calcDistance(p1, p2){
                return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
             }
</script>
<script type="text/javascript">
function getDirections() {
    var fromStr = fromInput.value;
    //alert(fromStr);
    var toStr = toInput.value;
    //alert(toStr);
    var dirRequest = {
      origin: fromStr,
      destination: toStr,
      travelMode: getSelectedTravelMode(),
      unitSystem: getSelectedUnitSystem(),
      provideRouteAlternatives: true
    };
    dirService.route(dirRequest, showDirections);
  }
  function getSelectedUnitSystem() {
    return unitInput.options[unitInput.selectedIndex].value == 'metric' ?
        google.maps.DirectionsUnitSystem.METRIC :
        google.maps.DirectionsUnitSystem.IMPERIAL;
  }
  function getSelectedTravelMode() {
    var value =
        travelModeInput.options[travelModeInput.selectedIndex].value;
    if (value == 'driving') {
      value = google.maps.DirectionsTravelMode.DRIVING;
    } else if (value == 'bicycling') {
      value = google.maps.DirectionsTravelMode.BICYCLING;
    } else if (value == 'walking') {
      value = google.maps.DirectionsTravelMode.WALKING;
    } else {
      alert('Unsupported travel mode.');
    }
    return value;
  }
  function showDirections(dirResult, dirStatus) {
      //alert(dirResult.routes.length);
    if (dirStatus != google.maps.DirectionsStatus.OK) {
      alert('Sorry, we could not calculate driving directions between these Locations');
      return;
    }
    // Show directions
    //Demo.dirRenderer.setMap(Demo.map);
    dirRenderer.setPanel(dirContainer);
    dirRenderer.setDirections(dirResult);
  }
// Onload handler to fire off the app.
//google.maps.event.addDomListener(window, 'load', Demo.init);
</script>
<script type='text/javascript'>
var dirvishnu = new Array();
var mydirser;
function calculateRoute(searchTextFieldSource, searchTextFieldDestination) {
    //alert(searchTextFieldSource);
    //alert(searchTextFieldDestination);
    // Center initialized to Naples, Italy
    var myOptions = {
        zoom: 10,
        center: new google.maps.LatLng(40.84, 14.25),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
        dirvishnu = new Array();
    // Draw the map
    var mapObject = new google.maps.Map(document.getElementById("map"), myOptions); 
    var trafficLayer = new google.maps.TrafficLayer();
    trafficLayer.setMap(mapObject);
    var directionsService = new google.maps.DirectionsService();
    var directionsRequest = 
    {
        origin: searchTextFieldSource,
        destination: searchTextFieldDestination,
        provideRouteAlternatives: true,
        travelMode: google.maps.DirectionsTravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC
    };
 directionsService.route(
    directionsRequest,
    function (response, status) 
    {
        var strokeColor;




        var _colour = '#00458E';
        var _strokeWeight = 4;
        var _strokeOpacity = 1.0;
        var _suppressMarkers = false;
        var checkbox_value = document.getElementById("routes_option").checked;
        //alert(checkbox_value);
        if (status == google.maps.DirectionsStatus.OK && document.getElementById("routes_option").checked == true) {
            //alert("multiple route");
            for (var i = 0, len = response.routes.length; i < len; i++) 
            {   
                dirvishnu[i] = new google.maps.DirectionsRenderer({


                      polylineOptions: 
                      {
                        strokeColor:'#'+Math.floor(Math.random()*16777215).toString(16),
                        strokeWeight: _strokeWeight, 
                      }, 
                    map: mapObject,
                    directions: response,
                    routeIndex: i
                });
            }
        } 
            else if (status == google.maps.DirectionsStatus.OK && document.getElementById("routes_option").checked == false) 
            {
                //alert("single route")
                for (var i = 0, len = response.routes.length; i < 1; i++) {
                    dirvishnu[i] = new google.maps.DirectionsRenderer({
                    polylineOptions: 
                      {
                        strokeColor: '#'+Math.floor(Math.random()*16777215).toString(16),
                      }, 
                        map: mapObject,
                        directions: response,
                        routeIndex: i
                    });
                }
            }
        else 
        {
            $("#error").append("Unable to retrieve your route<br />");
        }
        if(typeof mydirser != "undefined")
        {
            mydirser.setMap(null);
        }
        document.getElementById('dir-container').innerHTML='';
        mydirser = dirvishnu[0];
        mydirser.setPanel(document.getElementById('dir-container'));
    }
);


}
$(document).ready(function () 
    {
        var UserSource = document.getElementById('searchTextFieldSource');
        var UserDestination = document.getElementById('searchTextFieldDestination');
        var ACUserSource = new google.maps.places.Autocomplete(UserSource);
        var ACUserDestination = new google.maps.places.Autocomplete(UserDestination);
        $("#calculate-route").submit(function (event) 
        {
        event.preventDefault();
        calculateRoute($("#searchTextFieldSource").val(), $("#searchTextFieldDestination").val());
        });
    });
</script>
</body>
</html>

0 个答案:

没有答案