0
var docNo = '';
var arr = [];
var token = localStorage.getItem('accessToken');
var directionsService;
var directionsDisplay;
var itineraryDcoNo = '';
var MapPoints = [];
var flightPlanCoordinates = [];

//Load lon & lat data to as json object
function loadLongLatData(docNo) {
    MapPoints;
    var dataObject = {};
    dataObject.Doc_No = docNo;
    $('#loaderwrapper').show();
    var headers = {};
    headers.Authorization = 'Bearer ' + token;
    $.ajax({
        method: 'POST',
        url: loadLongLatDetailsLink,
        data: dataObject,
        headers: headers,
        datadataType: "",
        success: function (data) {

            MapPoints = data.Address;
            initializeMapReport();
            $('#loaderwrapper').hide();
            //var MapPoints = JSON.stringify(data.Address);

        },
        error: function () {
        $('#loaderwrapper').hide();
        var errorMessage = 'Error Retrieving Data'
        document.getElementById("errormessage").innerHTML = errorMessage;
        $("#errorModal").modal('show');

    }
    });

}

// end Load lon & lat data to as json object

// load map path function goes here

function initializeMapReport() {

if (jQuery('#map').length > 0) {

    var locations = MapPoints;

     directionsService = new google.maps.DirectionsService;
     directionsDisplay = new google.maps.DirectionsRenderer;
    //var locations = jQuery.parseJSON(MapPoints);

    window.map = new google.maps.Map(document.getElementById('map'), {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false,
    });


    var infowindow = new google.maps.InfoWindow();
     flightPlanCoordinates = [];
    var bounds = new google.maps.LatLngBounds();

    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i].Latitude.toString(), locations[i].Longitude.toString()),
            //position: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
            map: map
        });
        flightPlanCoordinates.push(marker.getPosition());
        bounds.extend(marker.position);

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent(locations[i]['AddressLocation']);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }

    map.fitBounds(bounds);
    //draw polyline path in the map
    var flightPath = new google.maps.Polyline({
        map: map,
        path: flightPlanCoordinates,
        strokeColor: "#FF0000",
        strokeOpacity: 1.0,
        strokeWeight: 2
    });


  }
}
//end map path function here

I need to implement google map which use the direction service API to generate route path and direction of map. Here in code snippet I already implemented google map load the markers which are taken from database. Then polyline was drawn. But I need to use direction service to generate path on my map.Some thing similer to this https://developers.google.com/maps/documentation/javascript/examples/directions-waypoints (Here "MapPoints[]" catch the json object from my C# webs service controller). map with polyline

Here is the print function I am using to print my map. But it is only render the map. It is not showing path and markers in side the map. I am using map inside the bootstrap model.

function PrintElem(elem) {
gmapPrint($(elem).html());
}

function printMaps() {
var body = $('modal-body-map');
var mapContainer = $('.map-container');
var mapContainerParent = mapContainer.parent();
var printContainer = $('<div>');

printContainer
    .addClass('print-container')
    .css('position', 'relative')
    .height(mapContainer.height())
    .append(mapContainer)
    .prependTo(body);

var content = body
    .children()
    .not('script')
    .not(printContainer)
    .detach();
 var patchedStyle = $('<style>')
    .attr('media', 'print')
    .text('img { max-width: none !important; }' +
          'a[href]:after { content: ""; }')
    .appendTo('head');

window.print();

body.prepend(content);
mapContainerParent.prepend(mapContainer);

printContainer.remove();
patchedStyle.remove();
}

function gmapPrint() {
var content = window.document.getElementById('map'); // get you map details
mapContainer = true;
printContainer = true;
var newWindow = window.open(); // open a new window
newWindow.document.write(content.innerHTML); // write the map into the new    window
newWindow.print(); // print the new window
newWindow.close();
}

Here is code snippet from my bootsrap model

 <div class="modal-footer modalfooterCustom">
                        <button type="button" id="closereportDataBtn" data-  dismiss="modal">close</button>
                        <button type="button" class="btn-primary"    id="savereportDataBtn"  onclick="PrintElem();" onfocus="window.close()">Print</button>

                    </div>
Haswin
  • 13
  • 5
  • [Related question (creates directions from GeoJson)](http://stackoverflow.com/questions/25272247/google-map-waypoints-from-geojson) – geocodezip Aug 09 '16 at 08:45
  • [Related question (creates directions from GeoJson)](http://stackoverflow.com/questions/25045140/google-map-itinerary-from-geojson-file) – geocodezip Aug 09 '16 at 08:47
  • possible duplicate of [How to make route direction between multiple markers](http://stackoverflow.com/questions/36523773/how-to-make-route-direction-between-multiple-markers) – geocodezip Aug 09 '16 at 08:48

1 Answers1

0

Using modified code from this question: How to make route direction between multiple markers

Get driving directions between 3 markers (origin, destination and one waypoint).

proof of concept fiddle

code snippet:

var directionsService;
var directionsDisplay;
var MapPoints = [];
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();

// load map path function goes here
function initializeMapReport() {
    if (jQuery('#map').length > 0) {
      var locations = MapPoints;
      directionsService = new google.maps.DirectionsService;
      directionsDisplay = new google.maps.DirectionsRenderer;
      window.map = new google.maps.Map(document.getElementById('map'), {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false,
      });

      var infowindow = new google.maps.InfoWindow();
      var bounds = new google.maps.LatLngBounds();
      directionsDisplay = new google.maps.DirectionsRenderer({
        map: window.map,
        suppressMarkers: true
      });
      var request = {
        travelMode: google.maps.TravelMode.DRIVING
      };
      for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
          position: new google.maps.LatLng(locations[i].Latitude.toString(), locations[i].Longitude.toString()),
          //position: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
          map: map
        });
        bounds.extend(marker.position);

        google.maps.event.addListener(marker, 'click', (function(marker, i) {
          return function() {
            infowindow.setContent(locations[i]['AddressLocation']);
            infowindow.open(map, marker);
          }
        })(marker, i));
        // create request from locations array, 1st marker is origin
        if (i == 0) request.origin = marker.getPosition();
        // last marker is destination
        else if (i == locations.length - 1) request.destination = marker.getPosition();
        else {
          // any other markers are waypoints
          if (!request.waypoints) request.waypoints = [];
          request.waypoints.push({
            location: marker.getPosition(),
            stopover: true
          });
        }
      }
      // call directions service
      directionsService.route(request, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(result);
        }
      });
      map.fitBounds(bounds);
    }
  }
  //end map path function here
google.maps.event.addDomListener(window, 'load', initializeMapReport);

// ============== test data ========================
//New York, NY, USA (40.7127837, -74.00594130000002)
//Newark, NJ, USA (40.735657, -74.1723667)
var MapPoints = [{
  Latitude: 42,
  Longitude: -72,
  AddressLocation: "New York"
}, {
  AddressLocation: "New York, NY, USA",
  Latitude: 40.7127837,
  Longitude: -74.0059413
}, {
  AddressLocation: "Newark, NJ, USA",
  Latitude: 40.735657,
  Longitude: -74.1723667
}];
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>
geocodezip
  • 158,664
  • 13
  • 220
  • 245