vendredi 16 mars 2018

Zoom in on origin on map when destination is unknown

I'm using Google Distance Matrix API to calculate distance between an origin and a destination. The destination is chosen by the user in a dropdown. There are markers on the map for the different locations in the dropdown.

If the user chooses "I don't know the closest destination" in the dropdown, I would like the map to zoom in and place a marker on the place of origin so that it's clearer what markers are closest to the origin and print the text "The markers indicate which place is closest to you".

Any tips on how I can do that? Thanks.

HTML

<form id="distance_form">
      <span>
        <label>Enter origin: </label>
      </span>
      <span>
        <input id="origin" type="text" name="origin"/>
      </span>
      <span>
        <label>Choose the closest destination</label>
      </span>
      <span>
        <select id="destination" class="js-example-basic-single" type="text" name="destination">
          <option value="I dont know">I don't know the closest destination</option>
          <option value="Marblehead, MA">Marblehead</option>
          <option value="Salem, MA">Salem</option>
          <option value="Boston, MA">Boston</option>
        </select>
        </span>
        <input id=submit type="submit" value="Calculate"/>
      </form>

      <div id="result"></div>
      <div id="map" class="mapCanvas"></div>

JavaScript

function initMap() {

var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 4.5,
  center: {lat: 42.4388, lng: -70.9917},
  mapTypeControlOptions: {
  mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain',
         'styled_map']
       }
});
directionsDisplay.setMap(map);

//Create and open InfoWindow.
var infoWindow = new google.maps.InfoWindow();

var icon = {
  url: "images/h_icon.svg", // url
  scaledSize: new google.maps.Size(50, 50), // scaled size

};

for (var i = 0; i < markers.length; i++) {
    var data = markers[i];
    var myLatlng = new google.maps.LatLng(data.lat, data.lng);
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: data.title,
        icon: icon
    });

    //Attach click event to the marker.
    (function (marker, data) {
        google.maps.event.addListener(marker, "click", function (e) {
            //Wrap the content inside an HTML DIV in order to set height and width of InfoWindow.
            infoWindow.setContent("<div style = 'width:350px;min-height:50px'>" + data.description + "</div>");
            infoWindow.open(map, marker);
        });
    })(marker, data);
}

var onChangeHandler = function() {
  calculateAndDisplayRoute(directionsService, directionsDisplay);
};

document.getElementById('submit').addEventListener('click', function() {
    calculateAndDisplayRoute(directionsService, directionsDisplay);
  });
}

function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
  origin: document.getElementById('origin').value,
  destination: document.getElementById('destination').value,
  travelMode: 'DRIVING'
}, function(response, status) {
  if (status === 'OK') {
    directionsDisplay.setDirections(response);
  }
});


//Resize Function
        google.maps.event.addDomListener(window, "resize", function() {
            var center = map.getCenter();
            google.maps.event.trigger(map, "resize");
            map.setCenter(center);
        });

}

//Distance Matrix

$(function(){
 function calculateDistance(origin, destination) {
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
    {
      origins: [origin],
      destinations: [destination],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,
      avoidHighways: false,
      avoidTolls: false
    }, callback);
  }

  function callback(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
      $('#result').html(err);
    } else {
      var origin = response.originAddresses[0];
      var destination = response.destinationAddresses[0];
      if (response.rows[0].elements[0].status === "ZERO_RESULTS") {
        $('#result').html("We can't seem to find "
                          + origin + ". Are you sure you entered a valid origin?");
      } else {
        var distance = response.rows[0].elements[0].distance;
        var duration = response.rows[0].elements[0].duration;
        var distance_value = distance.value;
        var distance_text = distance.text;
        var duration_value = duration.value;
        var duration_text = duration.text;
        var kilometer = distance_text.substring(0, distance_text.length - 3);

          $('#result_description').html("The driving distance from " + origin + " to " + destination + " is " + kilometer + " km and it takes " + duration_text + " to drive.");

        }

    }
  }

  $('#distance_form').submit(function(e){
      event.preventDefault();
      var origin = $('#origin').val();
      var destination = $('#destination').val();
      var distance_text = calculateDistance(origin, destination);
  });

});

Aucun commentaire:

Enregistrer un commentaire