Google Maps Directions服务不适用于自定义Infowindow [英] Google Maps direction service not working properly for custom Infowindow

查看:68
本文介绍了Google Maps Directions服务不适用于自定义Infowindow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建Google Maps Directions服务的从/到"点,并且这两种方法都可以工作-从地图单击从/到"并使用自动填充文本框,用户必须在其中填写从/到"目的地,并且两者均标记为地图. 最终它将在地图上绘制路线. 单独使用这两种方法,例如,如果我从/单击会绘制路线,但由于某种原因自定义Infowindow会出错. 应该如何工作: 首次单击地图时,应创建并打开自定义信息窗口发件人地址". 当您第二次单击地图时,它应该创建并打开自定义信息窗口收件人".

信息窗口的问题如下:

  1. Onclick,仅显示信息窗口发件人地址".
  2. 当您第二次单击地图并绘制路线时,两个标记都没有显示自定义信息窗口已打开,如果您单击标记,您会发现自定义信息窗口丢失了.

我准备了小提琴,在这里您可以看到几乎可以正常工作的DEMO:)

如果代码看起来一团糟,请原谅,但是为了重现此问题,我不得不删除了很多代码.

请帮助我解决以上问题

 var map;
var marker; // move marker definition into the global scope
var infowindow;
var uniqueId = 1;
var infoWindowcontent;
var markers = [];
function calculateAndDisplayRoute(directionsService, directionsRenderer) {
//console.log(marker);
  directionsService.route({
      origin: {
        query: document.getElementById('departure_address').value
      },
      destination: {
        query: document.getElementById('arrival_address').value
      },
      travelMode: 'DRIVING'
    },
    function(response, status) {
      if (status === 'OK') {
        var point = response.routes[0].legs[0];
        //console.log(point);
        directionsRenderer.setDirections(response);
		
		 createMarker(response.routes[0].legs[0].start_location, "A", "start marker", map, infowindow);
		var lastLeg = response.routes[0].legs.length - 1;
		createMarker(response.routes[0].legs[lastLeg].end_location, "B", "end marker", map, infowindow);
		//infowindow.open(map,marker);
        if (marker && marker.setMap) // hide click marker when directions displayed
          marker.setMap(null);
      } else {
        alert('Directions request failed due to ' + status);
      }
    });
}

function initMap_mobile() {
  var directionsService = new google.maps.DirectionsService();
  var directionsRenderer = new google.maps.DirectionsRenderer();
  var map = new google.maps.Map(document.getElementById('mobilemap'), {
    mapTypeControl: false,
    center: {
	lat: 42.700000762939, 
	lng: 23.333299636841
    },
    zoom: 13
  });
  directionsRenderer.setMap(map);
  //var infowindow;

  google.maps.event.addListener(map, 'click', function(event) {

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      'latLng': new google.maps.LatLng(event.latLng.lat(), event.latLng.lng())
    }, function(results, status) {
      //otherwise clicks twice
      set_lat_long(event.latLng.lat(), event.latLng.lng(), results[0].formatted_address, directionsService, directionsRenderer);
      
	   //alert(uniqueId);
	  if(uniqueId == 1){
	  label = 'From Address';
			infoWindowcontent = '<div class="ib infobox"><label style="font-weight:bold;text-transform: uppercase;">From Address:</label><hr><br/>'+results[0].formatted_address+'<br /><br /><button class="btn btn-block btn-primary btn-sm" onclick = "clear_dep();" value = "delete">Delete</button><br/></div>';
			}
			if(uniqueId == 2){
			label = 'To Address';
			infoWindowcontent = '<div class="ib infobox"><label style="font-weight:bold;text-transform: uppercase;">To Address:</label><hr><br/>'+results[0].formatted_address+'<br /><br /><button class="btn btn-block btn-primary btn-sm" onclick = "clear_arr();" value = "delete">Delete</button><br/></div>';
			}
	  if (marker == null) {
	  console.log(event.latLng);
        marker = new google.maps.Marker({
		position: event.latLng,
		draggable: true,
		label: {
			text: label,
			color: '#a2003b'
		},
		
		animation: google.maps.Animation.DROP,
		map: map
        });
		
	 
		marker.id = uniqueId;
      }else {
        marker.setPosition(event.latLng);
      }
	  
	  
		infowindow = new google.maps.InfoWindow({
		content: infoWindowcontent
	  });
    infowindow.open(map,marker);
		uniqueId++;

	  //Add marker to the array.
      markers.push(marker);
    });
  });
}



function createMarker(location, label, content, map, id) {
//console.log(location.lat);
  var marker = new google.maps.Marker({
    position: location,
   // label: label,
    title: label,
	id: id,
	icon: {
    url: 'https://maps.google.com/mapfiles/kml/pal4/icon31.png',
    // This marker is 20 pixels wide by 32 pixels high.
    // The anchor for this image is the base of the flagpole at (0, 32).
    anchor: new google.maps.Point(0, 0)
  },
    map: map
  });
  infowindow = new google.maps.InfoWindow({
   content: content,
   maxWidth: 350
});
	infowindow.setContent(content);
    infowindow.open(map, marker);
	
	//console.log(marker);
	markers.push(marker);
	
}

function set_lat_long(lat, lng, address, directionsService, directionsRenderer) {
  var dep_lat = $('#dep_lat').val();
  var dep_lng = $('#dep_lng').val();
  var arr_lat = $('#arr_lat').val();
  var arr_lng = $('#arr_lng').val();

  if (isEmpty(dep_lat) || isEmpty(dep_lng)) {
    //alert(dep_lat);
    $('#dep_lat').val(lat);
    $('#dep_lng').val(lng);
    $('#departure_address').val(address);
    $('#clear_dep').show();
  } else {
    if (isEmpty(arr_lat) || isEmpty(arr_lng)) {
      $('#arr_lat').val(lat);
      $('#arr_lng').val(lng);
      $('#arrival_address').val(address);
      $('#clear_arr,.arrival_address').show();
    }
  }

  if (!isEmpty($('#dep_lat').val()) && !isEmpty($('#dep_lng').val()) && !isEmpty($('#arr_lat').val()) && !isEmpty($('#arr_lng').val())) calculateAndDisplayRoute(directionsService, directionsRenderer);
}

function isEmpty(value) {
  return (value == null || value.length === 0);
}
initMap_mobile(); 

 #mobilemap {
  height: 500px;
  width: 100%;
  border: solid 1px #ddd;
}
input{margin:5px;}
.clear {

    cursor: pointer;

} 

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDdEHqLflmCXJ8MzV8tfJGVsvy2GYeQ7lg&libraries=places&callback=initMap_mobile" async defer></script>

<div class="cell-xs-12 mobw100 npr">
<div id="mode-selector" class="controls">Driving Mode selector
<input type="radio" name="type" id="changemode-driving" checked="checked" />  
</div>
  <div class="form-group text-right">
    <label for="departure_address" class="form-label">From</label>
    <input maxlength="100" id="departure_address" placeholder="From address" type="text" name="departure_address" class="controls form-control form-control-gray-base dybck" value="" style="background: rgb(255, 236, 236) none repeat scroll 0% 0%;" autocomplete="off">
<small id="clear_dep" onclick="clear_dep();" class="ib w100 tar clear" style="display: inline;">Clear address</small>
    <input type="hidden" name="dep_lat" id="dep_lat" value="">
    <input type="hidden" name="dep_lng" id="dep_lng" value="">
  </div>
</div>

<div class="cell-xs-12 offset-top-20 mobw100 npr he arrival_address">
  <div class="form-group text-right">
    <label for="arrival_address" class="form-label">To</label>
    <input maxlength="100" id="arrival_address" placeholder="To address" type="text" name="arrival_address" class="controls form-control form-control-gray-base" value="" autocomplete="off">
<small id="clear_arr" onclick="clear_arr();" class="ib w100 tar clear" style="display: inline;">Clear address</small>
    <input type="hidden" name="arr_lat" id="arr_lat" value="">
    <input type="hidden" name="arr_lng" id="arr_lng" value="">
  </div>
  
  <div class="cell-xs-12 offset-top-20 mobw100 npr he tal date date_hide">
                         <div class="form-group ib w50 vat">
                          <label for="date" class="form-label">Date</label>
                          <input readonly id="date" data-time-picker="date" type="text" name="travel_date" class="form-control form-control-gray-base dates" value="2019-09-10"/>
                        </div>
   <div class="cell-xs-12 offset-top-20 mobw100 npr he tal pax_adults mt10" style="display: block;">
<div class="form-group ib w50 ">
	  <label for="pax_adults" class="form-label fs11">Pax N</label>
	  <input min="1" id="pax_adults" type="number" name="pax_adults" class="p5 form-control form-control-gray-base" value="" style="background: rgb(255, 255, 255) none repeat scroll 0% 0%;">
 </div>
</div> 

<div class="cell-xs-12 offset-top-20 npr he hm tal colback mt10" style="display: block;">
			   <div class="form-group nmb ib w100 tac"><h6 id="show_more" class="option-heading">Travel info</h6><hr></div>
				
				<div class="form-group nmb ib w100 tac mtb10 option-content is-hidden">
				<div class="form-group nmb ib w100 tac mtb10">
				<div class="form-group nmb ib w50 tac">
			   <label for="travel_distance" class="form-label">Distance</label>
			   <input readonly="" type="text" name="travel_distance" id="travel_distance" value="">
			    </div>
			   <div class="form-group nmb ib w50 tac">
				<label for="travel_time" class="form-label">Travel duration</label>
			   <input readonly="" type="hidden" name="normal_travel_time" id="normal_travel_time" value="">
			   <input readonly="" type="text" name="travel_time" id="travel_time" value="">
			    </div>
			    </div>
			   
			   <div class="form-group nmb ib w100 tac mtb10">
			   <label for="travel_price" class="form-label">Travel price USD</label>
			   <input readonly="" class="ib" type="text" name="travel_price" id="travel_price" value=""> 
			    </div>
				<hr>
			    </div>				
				
			   </div>
</div>
<div id="mobilemap"></div> 

提前感谢您的时间

解决方案

  1. 您的全局map变量未初始化.您需要将其传递到createMarker函数(可从directionRenderer.getMap()获得)或初始化全局map变量(通过删除初始化地图的行中的var).

  2. 您需要隐藏路线渲染器(var directionsRenderer = new google.maps.DirectionsRenderer({suppressMarkers: true});)

  3. 创建的标记

 var marker; // move marker definition into the global scope
var infowindow;
var uniqueId = 1;
var infoWindowcontent;
var markers = [];

function calculateAndDisplayRoute(directionsService, directionsRenderer) {
  directionsService.route({
      origin: {
        query: document.getElementById('departure_address').value
      },
      destination: {
        query: document.getElementById('arrival_address').value
      },
      travelMode: 'DRIVING'
    },
    function(response, status) {
      if (status === 'OK') {
        var point = response.routes[0].legs[0];
        directionsRenderer.setDirections(response);

        createMarker(response.routes[0].legs[0].start_location, "A", "start marker", directionsRenderer.getMap(), infowindow);
        var lastLeg = response.routes[0].legs.length - 1;
        createMarker(response.routes[0].legs[lastLeg].end_location, "B", "end marker", directionsRenderer.getMap(), infowindow);
        if (marker && marker.setMap) // hide click marker when directions displayed
          marker.setMap(null);
      } else {
        alert('Directions request failed due to ' + status);
      }
    });
}

function initMap_mobile() {
  var directionsService = new google.maps.DirectionsService();
  var directionsRenderer = new google.maps.DirectionsRenderer({
    suppressMarkers: true
  });
  map = new google.maps.Map(document.getElementById('mobilemap'), {
    mapTypeControl: false,
    center: {
      lat: 42.700000762939,
      lng: 23.333299636841
    },
    zoom: 13
  });
  directionsRenderer.setMap(map);

  google.maps.event.addListener(map, 'click', function(event) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      'latLng': new google.maps.LatLng(event.latLng.lat(), event.latLng.lng())
    }, function(results, status) {
      //otherwise clicks twice
      set_lat_long(event.latLng.lat(), event.latLng.lng(), results[0].formatted_address, directionsService, directionsRenderer);

      if (uniqueId == 1) {
        label = 'From Address';
        infoWindowcontent = '<div class="ib infobox"><label style="font-weight:bold;text-transform: uppercase;">From Address:</label><hr><br/>' + results[0].formatted_address + '<br /><br /><button class="btn btn-block btn-primary btn-sm" onclick = "clear_dep();" value = "delete">Delete</button><br/></div>';
      }
      if (uniqueId == 2) {
        label = 'To Address';
        infoWindowcontent = '<div class="ib infobox"><label style="font-weight:bold;text-transform: uppercase;">To Address:</label><hr><br/>' + results[0].formatted_address + '<br /><br /><button class="btn btn-block btn-primary btn-sm" onclick = "clear_arr();" value = "delete">Delete</button><br/></div>';
      }
      if (marker == null) {
        console.log(event.latLng);
        marker = new google.maps.Marker({
          position: event.latLng,
          draggable: true,
          label: {
            text: label,
            color: '#a2003b'
          },

          animation: google.maps.Animation.DROP,
          map: map
        });
        marker.id = uniqueId;
      } else {
        marker.setPosition(event.latLng);
      }
      infowindow = new google.maps.InfoWindow({
        content: infoWindowcontent
      });
      infowindow.open(map, marker);
      uniqueId++;

      //Add marker to the array.
      markers.push(marker);
    });
  });
}

function createMarker(location, label, content, map, id) {
  var marker = new google.maps.Marker({
    position: location,
    title: label,
    id: id,
    icon: {
      url: 'https://maps.google.com/mapfiles/kml/pal4/icon31.png',
      // This marker is 20 pixels wide by 32 pixels high.
      // The anchor for this image is the base of the flagpole at (0, 32).
      anchor: new google.maps.Point(0, 0)
    },
    map: map
  });
  infowindow = new google.maps.InfoWindow({
    content: content,
    maxWidth: 350
  });
  infowindow.setContent(content);
  infowindow.open(map, marker);
  markers.push(marker);
}

function set_lat_long(lat, lng, address, directionsService, directionsRenderer) {
  var dep_lat = $('#dep_lat').val();
  var dep_lng = $('#dep_lng').val();
  var arr_lat = $('#arr_lat').val();
  var arr_lng = $('#arr_lng').val();

  if (isEmpty(dep_lat) || isEmpty(dep_lng)) {
    //alert(dep_lat);
    $('#dep_lat').val(lat);
    $('#dep_lng').val(lng);
    $('#departure_address').val(address);
    $('#clear_dep').show();
  } else {
    if (isEmpty(arr_lat) || isEmpty(arr_lng)) {
      $('#arr_lat').val(lat);
      $('#arr_lng').val(lng);
      $('#arrival_address').val(address);
      $('#clear_arr,.arrival_address').show();
    }
  }

  if (!isEmpty($('#dep_lat').val()) && !isEmpty($('#dep_lng').val()) && !isEmpty($('#arr_lat').val()) && !isEmpty($('#arr_lng').val())) calculateAndDisplayRoute(directionsService, directionsRenderer);
}

function isEmpty(value) {
  return (value == null || value.length === 0);
}
initMap_mobile(); 

 #mobilemap {
  height: 500px;
  width: 100%;
  border: solid 1px #ddd;
}

input {
  margin: 5px;
}

.clear {
  cursor: pointer;
} 

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap_mobile" async defer></script>

<div class="cell-xs-12 mobw100 npr">
  <div id="mode-selector" class="controls">Driving Mode selector
    <input type="radio" name="type" id="changemode-driving" checked="checked" />
  </div>
  <div class="form-group text-right">
    <label for="departure_address" class="form-label">From</label>
    <input maxlength="100" id="departure_address" placeholder="From address" type="text" name="departure_address" class="controls form-control form-control-gray-base dybck" value="" style="background: rgb(255, 236, 236) none repeat scroll 0% 0%;" autocomplete="off">
    <small id="clear_dep" onclick="clear_dep();" class="ib w100 tar clear" style="display: inline;">Clear address</small>
    <input type="hidden" name="dep_lat" id="dep_lat" value="">
    <input type="hidden" name="dep_lng" id="dep_lng" value="">
  </div>
</div>

<div class="cell-xs-12 offset-top-20 mobw100 npr he arrival_address">
  <div class="form-group text-right">
    <label for="arrival_address" class="form-label">To</label>
    <input maxlength="100" id="arrival_address" placeholder="To address" type="text" name="arrival_address" class="controls form-control form-control-gray-base" value="" autocomplete="off">
    <small id="clear_arr" onclick="clear_arr();" class="ib w100 tar clear" style="display: inline;">Clear address</small>
    <input type="hidden" name="arr_lat" id="arr_lat" value="">
    <input type="hidden" name="arr_lng" id="arr_lng" value="">
  </div>

  <div class="cell-xs-12 offset-top-20 mobw100 npr he tal date date_hide">
    <div class="form-group ib w50 vat">
      <label for="date" class="form-label">Date</label>
      <input readonly id="date" data-time-picker="date" type="text" name="travel_date" class="form-control form-control-gray-base dates" value="2019-09-10" />
    </div>
    <div class="cell-xs-12 offset-top-20 mobw100 npr he tal pax_adults mt10" style="display: block;">
      <div class="form-group ib w50 ">
        <label for="pax_adults" class="form-label fs11">Pax N</label>
        <input min="1" id="pax_adults" type="number" name="pax_adults" class="p5 form-control form-control-gray-base" value="" style="background: rgb(255, 255, 255) none repeat scroll 0% 0%;">
      </div>
    </div>

    <div class="cell-xs-12 offset-top-20 npr he hm tal colback mt10" style="display: block;">
      <div class="form-group nmb ib w100 tac">
        <h6 id="show_more" class="option-heading">Travel info</h6>
        <hr>
      </div>

      <div class="form-group nmb ib w100 tac mtb10 option-content is-hidden">
        <div class="form-group nmb ib w100 tac mtb10">
          <div class="form-group nmb ib w50 tac">
            <label for="travel_distance" class="form-label">Distance</label>
            <input readonly="" type="text" name="travel_distance" id="travel_distance" value="">
          </div>
          <div class="form-group nmb ib w50 tac">
            <label for="travel_time" class="form-label">Travel duration</label>
            <input readonly="" type="hidden" name="normal_travel_time" id="normal_travel_time" value="">
            <input readonly="" type="text" name="travel_time" id="travel_time" value="">
          </div>
        </div>

        <div class="form-group nmb ib w100 tac mtb10">
          <label for="travel_price" class="form-label">Travel price USD</label>
          <input readonly="" class="ib" type="text" name="travel_price" id="travel_price" value="">
        </div>
        <hr>
      </div>

    </div>
  </div>
  <div id="mobilemap"></div> 

I have to create Google Maps direction service From / To points and it should work both - from map clicks From /To and using autocomplete text boxes where user has to fill in From /To destinations and both to be marked as markers on the map. Finally it will draw route on the map. Using separately both work, for example if I click from / to it will draw the route, but for some reason gets wrong custom Infowindow. How it is supposed to work: When you click on map for first time it should create and OPEN custom Infowindow "From address". When you click on map for second time it should create and OPEN custom Infowindow "To address".

The problems with the Infowindow are as following:

  1. Onclick, It only shows Infowindow "From address".
  2. When you click on the map for a second time and the route is draw both markers are not showing the custom Infowindows OPENED and if you click on the marker you will discover that the custom Infowindows are missing.

I have prepared a fiddle where you can see nearly working DEMO :)

Please excuse me if the code looks mess, but I had to remove a lot of code in order to reproduce the problem.

Please help me to fix the above problems

var map;
var marker; // move marker definition into the global scope
var infowindow;
var uniqueId = 1;
var infoWindowcontent;
var markers = [];
function calculateAndDisplayRoute(directionsService, directionsRenderer) {
//console.log(marker);
  directionsService.route({
      origin: {
        query: document.getElementById('departure_address').value
      },
      destination: {
        query: document.getElementById('arrival_address').value
      },
      travelMode: 'DRIVING'
    },
    function(response, status) {
      if (status === 'OK') {
        var point = response.routes[0].legs[0];
        //console.log(point);
        directionsRenderer.setDirections(response);
		
		 createMarker(response.routes[0].legs[0].start_location, "A", "start marker", map, infowindow);
		var lastLeg = response.routes[0].legs.length - 1;
		createMarker(response.routes[0].legs[lastLeg].end_location, "B", "end marker", map, infowindow);
		//infowindow.open(map,marker);
        if (marker && marker.setMap) // hide click marker when directions displayed
          marker.setMap(null);
      } else {
        alert('Directions request failed due to ' + status);
      }
    });
}

function initMap_mobile() {
  var directionsService = new google.maps.DirectionsService();
  var directionsRenderer = new google.maps.DirectionsRenderer();
  var map = new google.maps.Map(document.getElementById('mobilemap'), {
    mapTypeControl: false,
    center: {
	lat: 42.700000762939, 
	lng: 23.333299636841
    },
    zoom: 13
  });
  directionsRenderer.setMap(map);
  //var infowindow;

  google.maps.event.addListener(map, 'click', function(event) {

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      'latLng': new google.maps.LatLng(event.latLng.lat(), event.latLng.lng())
    }, function(results, status) {
      //otherwise clicks twice
      set_lat_long(event.latLng.lat(), event.latLng.lng(), results[0].formatted_address, directionsService, directionsRenderer);
      
	   //alert(uniqueId);
	  if(uniqueId == 1){
	  label = 'From Address';
			infoWindowcontent = '<div class="ib infobox"><label style="font-weight:bold;text-transform: uppercase;">From Address:</label><hr><br/>'+results[0].formatted_address+'<br /><br /><button class="btn btn-block btn-primary btn-sm" onclick = "clear_dep();" value = "delete">Delete</button><br/></div>';
			}
			if(uniqueId == 2){
			label = 'To Address';
			infoWindowcontent = '<div class="ib infobox"><label style="font-weight:bold;text-transform: uppercase;">To Address:</label><hr><br/>'+results[0].formatted_address+'<br /><br /><button class="btn btn-block btn-primary btn-sm" onclick = "clear_arr();" value = "delete">Delete</button><br/></div>';
			}
	  if (marker == null) {
	  console.log(event.latLng);
        marker = new google.maps.Marker({
		position: event.latLng,
		draggable: true,
		label: {
			text: label,
			color: '#a2003b'
		},
		
		animation: google.maps.Animation.DROP,
		map: map
        });
		
	 
		marker.id = uniqueId;
      }else {
        marker.setPosition(event.latLng);
      }
	  
	  
		infowindow = new google.maps.InfoWindow({
		content: infoWindowcontent
	  });
    infowindow.open(map,marker);
		uniqueId++;

	  //Add marker to the array.
      markers.push(marker);
    });
  });
}



function createMarker(location, label, content, map, id) {
//console.log(location.lat);
  var marker = new google.maps.Marker({
    position: location,
   // label: label,
    title: label,
	id: id,
	icon: {
    url: 'https://maps.google.com/mapfiles/kml/pal4/icon31.png',
    // This marker is 20 pixels wide by 32 pixels high.
    // The anchor for this image is the base of the flagpole at (0, 32).
    anchor: new google.maps.Point(0, 0)
  },
    map: map
  });
  infowindow = new google.maps.InfoWindow({
   content: content,
   maxWidth: 350
});
	infowindow.setContent(content);
    infowindow.open(map, marker);
	
	//console.log(marker);
	markers.push(marker);
	
}

function set_lat_long(lat, lng, address, directionsService, directionsRenderer) {
  var dep_lat = $('#dep_lat').val();
  var dep_lng = $('#dep_lng').val();
  var arr_lat = $('#arr_lat').val();
  var arr_lng = $('#arr_lng').val();

  if (isEmpty(dep_lat) || isEmpty(dep_lng)) {
    //alert(dep_lat);
    $('#dep_lat').val(lat);
    $('#dep_lng').val(lng);
    $('#departure_address').val(address);
    $('#clear_dep').show();
  } else {
    if (isEmpty(arr_lat) || isEmpty(arr_lng)) {
      $('#arr_lat').val(lat);
      $('#arr_lng').val(lng);
      $('#arrival_address').val(address);
      $('#clear_arr,.arrival_address').show();
    }
  }

  if (!isEmpty($('#dep_lat').val()) && !isEmpty($('#dep_lng').val()) && !isEmpty($('#arr_lat').val()) && !isEmpty($('#arr_lng').val())) calculateAndDisplayRoute(directionsService, directionsRenderer);
}

function isEmpty(value) {
  return (value == null || value.length === 0);
}
initMap_mobile();

#mobilemap {
  height: 500px;
  width: 100%;
  border: solid 1px #ddd;
}
input{margin:5px;}
.clear {

    cursor: pointer;

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDdEHqLflmCXJ8MzV8tfJGVsvy2GYeQ7lg&libraries=places&callback=initMap_mobile" async defer></script>

<div class="cell-xs-12 mobw100 npr">
<div id="mode-selector" class="controls">Driving Mode selector
<input type="radio" name="type" id="changemode-driving" checked="checked" />  
</div>
  <div class="form-group text-right">
    <label for="departure_address" class="form-label">From</label>
    <input maxlength="100" id="departure_address" placeholder="From address" type="text" name="departure_address" class="controls form-control form-control-gray-base dybck" value="" style="background: rgb(255, 236, 236) none repeat scroll 0% 0%;" autocomplete="off">
<small id="clear_dep" onclick="clear_dep();" class="ib w100 tar clear" style="display: inline;">Clear address</small>
    <input type="hidden" name="dep_lat" id="dep_lat" value="">
    <input type="hidden" name="dep_lng" id="dep_lng" value="">
  </div>
</div>

<div class="cell-xs-12 offset-top-20 mobw100 npr he arrival_address">
  <div class="form-group text-right">
    <label for="arrival_address" class="form-label">To</label>
    <input maxlength="100" id="arrival_address" placeholder="To address" type="text" name="arrival_address" class="controls form-control form-control-gray-base" value="" autocomplete="off">
<small id="clear_arr" onclick="clear_arr();" class="ib w100 tar clear" style="display: inline;">Clear address</small>
    <input type="hidden" name="arr_lat" id="arr_lat" value="">
    <input type="hidden" name="arr_lng" id="arr_lng" value="">
  </div>
  
  <div class="cell-xs-12 offset-top-20 mobw100 npr he tal date date_hide">
                         <div class="form-group ib w50 vat">
                          <label for="date" class="form-label">Date</label>
                          <input readonly id="date" data-time-picker="date" type="text" name="travel_date" class="form-control form-control-gray-base dates" value="2019-09-10"/>
                        </div>
   <div class="cell-xs-12 offset-top-20 mobw100 npr he tal pax_adults mt10" style="display: block;">
<div class="form-group ib w50 ">
	  <label for="pax_adults" class="form-label fs11">Pax N</label>
	  <input min="1" id="pax_adults" type="number" name="pax_adults" class="p5 form-control form-control-gray-base" value="" style="background: rgb(255, 255, 255) none repeat scroll 0% 0%;">
 </div>
</div> 

<div class="cell-xs-12 offset-top-20 npr he hm tal colback mt10" style="display: block;">
			   <div class="form-group nmb ib w100 tac"><h6 id="show_more" class="option-heading">Travel info</h6><hr></div>
				
				<div class="form-group nmb ib w100 tac mtb10 option-content is-hidden">
				<div class="form-group nmb ib w100 tac mtb10">
				<div class="form-group nmb ib w50 tac">
			   <label for="travel_distance" class="form-label">Distance</label>
			   <input readonly="" type="text" name="travel_distance" id="travel_distance" value="">
			    </div>
			   <div class="form-group nmb ib w50 tac">
				<label for="travel_time" class="form-label">Travel duration</label>
			   <input readonly="" type="hidden" name="normal_travel_time" id="normal_travel_time" value="">
			   <input readonly="" type="text" name="travel_time" id="travel_time" value="">
			    </div>
			    </div>
			   
			   <div class="form-group nmb ib w100 tac mtb10">
			   <label for="travel_price" class="form-label">Travel price USD</label>
			   <input readonly="" class="ib" type="text" name="travel_price" id="travel_price" value=""> 
			    </div>
				<hr>
			    </div>				
				
			   </div>
</div>
<div id="mobilemap"></div>

Thank you in advance for your time

解决方案

  1. your global map variable is not initialized. You need to either pass it into the createMarker function (it is available from directionRenderer.getMap()) or initialize the global map variable (by removing the var in the line that initializes the map).

  2. you need to suppress the markers created by the directions renderer (var directionsRenderer = new google.maps.DirectionsRenderer({suppressMarkers: true});)

var marker; // move marker definition into the global scope
var infowindow;
var uniqueId = 1;
var infoWindowcontent;
var markers = [];

function calculateAndDisplayRoute(directionsService, directionsRenderer) {
  directionsService.route({
      origin: {
        query: document.getElementById('departure_address').value
      },
      destination: {
        query: document.getElementById('arrival_address').value
      },
      travelMode: 'DRIVING'
    },
    function(response, status) {
      if (status === 'OK') {
        var point = response.routes[0].legs[0];
        directionsRenderer.setDirections(response);

        createMarker(response.routes[0].legs[0].start_location, "A", "start marker", directionsRenderer.getMap(), infowindow);
        var lastLeg = response.routes[0].legs.length - 1;
        createMarker(response.routes[0].legs[lastLeg].end_location, "B", "end marker", directionsRenderer.getMap(), infowindow);
        if (marker && marker.setMap) // hide click marker when directions displayed
          marker.setMap(null);
      } else {
        alert('Directions request failed due to ' + status);
      }
    });
}

function initMap_mobile() {
  var directionsService = new google.maps.DirectionsService();
  var directionsRenderer = new google.maps.DirectionsRenderer({
    suppressMarkers: true
  });
  map = new google.maps.Map(document.getElementById('mobilemap'), {
    mapTypeControl: false,
    center: {
      lat: 42.700000762939,
      lng: 23.333299636841
    },
    zoom: 13
  });
  directionsRenderer.setMap(map);

  google.maps.event.addListener(map, 'click', function(event) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      'latLng': new google.maps.LatLng(event.latLng.lat(), event.latLng.lng())
    }, function(results, status) {
      //otherwise clicks twice
      set_lat_long(event.latLng.lat(), event.latLng.lng(), results[0].formatted_address, directionsService, directionsRenderer);

      if (uniqueId == 1) {
        label = 'From Address';
        infoWindowcontent = '<div class="ib infobox"><label style="font-weight:bold;text-transform: uppercase;">From Address:</label><hr><br/>' + results[0].formatted_address + '<br /><br /><button class="btn btn-block btn-primary btn-sm" onclick = "clear_dep();" value = "delete">Delete</button><br/></div>';
      }
      if (uniqueId == 2) {
        label = 'To Address';
        infoWindowcontent = '<div class="ib infobox"><label style="font-weight:bold;text-transform: uppercase;">To Address:</label><hr><br/>' + results[0].formatted_address + '<br /><br /><button class="btn btn-block btn-primary btn-sm" onclick = "clear_arr();" value = "delete">Delete</button><br/></div>';
      }
      if (marker == null) {
        console.log(event.latLng);
        marker = new google.maps.Marker({
          position: event.latLng,
          draggable: true,
          label: {
            text: label,
            color: '#a2003b'
          },

          animation: google.maps.Animation.DROP,
          map: map
        });
        marker.id = uniqueId;
      } else {
        marker.setPosition(event.latLng);
      }
      infowindow = new google.maps.InfoWindow({
        content: infoWindowcontent
      });
      infowindow.open(map, marker);
      uniqueId++;

      //Add marker to the array.
      markers.push(marker);
    });
  });
}

function createMarker(location, label, content, map, id) {
  var marker = new google.maps.Marker({
    position: location,
    title: label,
    id: id,
    icon: {
      url: 'https://maps.google.com/mapfiles/kml/pal4/icon31.png',
      // This marker is 20 pixels wide by 32 pixels high.
      // The anchor for this image is the base of the flagpole at (0, 32).
      anchor: new google.maps.Point(0, 0)
    },
    map: map
  });
  infowindow = new google.maps.InfoWindow({
    content: content,
    maxWidth: 350
  });
  infowindow.setContent(content);
  infowindow.open(map, marker);
  markers.push(marker);
}

function set_lat_long(lat, lng, address, directionsService, directionsRenderer) {
  var dep_lat = $('#dep_lat').val();
  var dep_lng = $('#dep_lng').val();
  var arr_lat = $('#arr_lat').val();
  var arr_lng = $('#arr_lng').val();

  if (isEmpty(dep_lat) || isEmpty(dep_lng)) {
    //alert(dep_lat);
    $('#dep_lat').val(lat);
    $('#dep_lng').val(lng);
    $('#departure_address').val(address);
    $('#clear_dep').show();
  } else {
    if (isEmpty(arr_lat) || isEmpty(arr_lng)) {
      $('#arr_lat').val(lat);
      $('#arr_lng').val(lng);
      $('#arrival_address').val(address);
      $('#clear_arr,.arrival_address').show();
    }
  }

  if (!isEmpty($('#dep_lat').val()) && !isEmpty($('#dep_lng').val()) && !isEmpty($('#arr_lat').val()) && !isEmpty($('#arr_lng').val())) calculateAndDisplayRoute(directionsService, directionsRenderer);
}

function isEmpty(value) {
  return (value == null || value.length === 0);
}
initMap_mobile();

#mobilemap {
  height: 500px;
  width: 100%;
  border: solid 1px #ddd;
}

input {
  margin: 5px;
}

.clear {
  cursor: pointer;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap_mobile" async defer></script>

<div class="cell-xs-12 mobw100 npr">
  <div id="mode-selector" class="controls">Driving Mode selector
    <input type="radio" name="type" id="changemode-driving" checked="checked" />
  </div>
  <div class="form-group text-right">
    <label for="departure_address" class="form-label">From</label>
    <input maxlength="100" id="departure_address" placeholder="From address" type="text" name="departure_address" class="controls form-control form-control-gray-base dybck" value="" style="background: rgb(255, 236, 236) none repeat scroll 0% 0%;" autocomplete="off">
    <small id="clear_dep" onclick="clear_dep();" class="ib w100 tar clear" style="display: inline;">Clear address</small>
    <input type="hidden" name="dep_lat" id="dep_lat" value="">
    <input type="hidden" name="dep_lng" id="dep_lng" value="">
  </div>
</div>

<div class="cell-xs-12 offset-top-20 mobw100 npr he arrival_address">
  <div class="form-group text-right">
    <label for="arrival_address" class="form-label">To</label>
    <input maxlength="100" id="arrival_address" placeholder="To address" type="text" name="arrival_address" class="controls form-control form-control-gray-base" value="" autocomplete="off">
    <small id="clear_arr" onclick="clear_arr();" class="ib w100 tar clear" style="display: inline;">Clear address</small>
    <input type="hidden" name="arr_lat" id="arr_lat" value="">
    <input type="hidden" name="arr_lng" id="arr_lng" value="">
  </div>

  <div class="cell-xs-12 offset-top-20 mobw100 npr he tal date date_hide">
    <div class="form-group ib w50 vat">
      <label for="date" class="form-label">Date</label>
      <input readonly id="date" data-time-picker="date" type="text" name="travel_date" class="form-control form-control-gray-base dates" value="2019-09-10" />
    </div>
    <div class="cell-xs-12 offset-top-20 mobw100 npr he tal pax_adults mt10" style="display: block;">
      <div class="form-group ib w50 ">
        <label for="pax_adults" class="form-label fs11">Pax N</label>
        <input min="1" id="pax_adults" type="number" name="pax_adults" class="p5 form-control form-control-gray-base" value="" style="background: rgb(255, 255, 255) none repeat scroll 0% 0%;">
      </div>
    </div>

    <div class="cell-xs-12 offset-top-20 npr he hm tal colback mt10" style="display: block;">
      <div class="form-group nmb ib w100 tac">
        <h6 id="show_more" class="option-heading">Travel info</h6>
        <hr>
      </div>

      <div class="form-group nmb ib w100 tac mtb10 option-content is-hidden">
        <div class="form-group nmb ib w100 tac mtb10">
          <div class="form-group nmb ib w50 tac">
            <label for="travel_distance" class="form-label">Distance</label>
            <input readonly="" type="text" name="travel_distance" id="travel_distance" value="">
          </div>
          <div class="form-group nmb ib w50 tac">
            <label for="travel_time" class="form-label">Travel duration</label>
            <input readonly="" type="hidden" name="normal_travel_time" id="normal_travel_time" value="">
            <input readonly="" type="text" name="travel_time" id="travel_time" value="">
          </div>
        </div>

        <div class="form-group nmb ib w100 tac mtb10">
          <label for="travel_price" class="form-label">Travel price USD</label>
          <input readonly="" class="ib" type="text" name="travel_price" id="travel_price" value="">
        </div>
        <hr>
      </div>

    </div>
  </div>
  <div id="mobilemap"></div>

这篇关于Google Maps Directions服务不适用于自定义Infowindow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆