Skip to content Skip to sidebar Skip to footer

Google Map Api - Directions Service Does Not Auto Zoom When The Map In A Modal

I have the following function to show direction between 2 lats and lngs to user $(document).ready(function(){ initialize_direction(); }); function initialize_direction() {

Solution 1:

Call initialize_direction(); on modal open. Try Like below it may help.

 $(document).ready(function(){
	  $( "#direction_modal" ).on('shown.bs.modal', function(){
	    initialize_direction();
	  });
	});

	functioninitialize_direction() {
	    var directionDisplay;
	    var directionsService = new google.maps.DirectionsService();
	    var direction_map;

	    directionDisplay = new google.maps.DirectionsRenderer();
	    var myOptions = {
	        mapTypeId: google.maps.MapTypeId.ROADMAP,
	    }
	    direction_map = new google.maps.Map(document.getElementById("direction_canvas"), myOptions);
	    directionDisplay.setMap(direction_map);

	    var start = '51.5074, 0.1278';
	    var end = '51.2074, 0.1278';
	    var request = {
	        origin:start,
	        destination:end,
	        travelMode: google.maps.DirectionsTravelMode.DRIVING
	    };
	    directionsService.route(request, function(response, status) {
	        if (status == google.maps.DirectionsStatus.OK) {
	            directionDisplay.setDirections(response);
	        }
	    });
	}
<title>Bootstrap Example</title><metacharset="utf-8"><metaname="viewport"content="width=device-width, initial-scale=1"><linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script><scriptsrc="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=AIzaSyAmqnSK2LDuPesG7GMG9thy_KDDmKnr7Zk"></script><divclass="container"><h2>Modal Example</h2><!-- Trigger the modal with a button --><buttontype="button"class="btn btn-info btn-lg"data-toggle="modal"data-target="#direction_modal">Open Modal</button><!-- Modal content--><divclass="modal fade"id="direction_modal"role="dialog"><divclass="modal-dialog modal-lg"><divclass="modal-content"><divclass="modal-header"><buttontype="button"class="close"data-dismiss="modal">&times;</button><h4class="modal-title">Direction to restaurant</h4></div><divclass="modal-body"><divid="direction_canvas"style="width:100%;height:400px;"></div></div></div></div></div>

Solution 2:

I was getting same issue on fancybox. Try below code to achieve the same.

varmap = new google.maps.Map(document.getElementById('map'), {
        zoom: 7,
        center: {
            lat: //your lat,
            lng: //your lng
        }
    });
    //startmap.setOptions({minZoom: 7});

Post a Comment for "Google Map Api - Directions Service Does Not Auto Zoom When The Map In A Modal"