在HTML中的模态中添加Google地图

时间:2016-01-27 12:00:52

标签: javascript html css google-maps-api-3

我有一个工作距离计算器,我使用Google API。因为这会在我的网站上占用大量空间,所以我决定把它放在Modal中。

问题在于地图本身已经消失,而且计算不再有效..请参见截图。

enter image description here

当我在没有模态的空HTML文件中使用此计算器时,它确实有效。

enter image description here

所以我的模态代码是:

<button style="margin:7px 15px 17px 0;" type="button" class="btn btn-success btn-lg" data-toggle="modal" data-target="#myModal">Bereken nu met korting!</button>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">

    <!-- Modal content-->
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
            <p>
                <label for="start">Start: </label>
                <input type="text" name="start" id="start" />
                <label for="end">End: </label>
                <input type="text" name="end" id="end" />
                <input type="submit" value="Calculate Route" onclick="calcRoute()" />
            </p>
            <p>
                <label for="distance">Distance (km): </label>
                <input type="text" name="distance" id="distance" readonly="true" />
                <input type="text" name="durationH" id="timeH" readonly="true" />
                <input type="text" name="durationM" id="timeM" readonly="true" />
            </p>
        </div>
        <div class="modal-body" id="map_canvas"></div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>

</div>

我使用的JS是:

var directionDisplay;
var map;

function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var melbourne = new google.maps.LatLng(51.6904085, 5.29543006);
var myOptions = {
    zoom:12,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: melbourne
}

map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}

var directionsService = new google.maps.DirectionsService();

function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var distanceInput = document.getElementById("distance");
var hours = document.getElementById("timeH");
var minutes = document.getElementById("timeM");

var request = {
    origin:start,
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
};

directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
        distanceInput.value = response.routes[0].legs[0].distance.value / 1000;
        <!-- Added this myself-->
        hours.value = parseInt( response.routes[0].legs[0].duration.value / 3600) % 24;
        minutes.value = parseInt( response.routes[0].legs[0].duration.value / 60) % 60;
        <!-- END Adding-->
    }
});
}

CSS很简单:

#map_canvas {
height: 100%;
}

2 个答案:

答案 0 :(得分:2)

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-7s5uDGW3AHqw6xtJmNNtr+OBRJUlgkNJEo78P4b0yRw= sha512-nNo+yCHEyn0smMxSswnf/OnX6/KwJuZTlNZBjauKhTK0c+zT+q5JOCx0UFhXQ6rJR9jg6Es8gPuD2uZcYDLqSw==" crossorigin="anonymous">
    <style>
        #map_canvas {
            height: 100%;
        }
    </style>
    <button style="margin:7px 15px 17px 0;" type="button" class="btn btn-success btn-lg" data-toggle="modal" data-target="#myModal">Bereken nu met korting!</button>
    <div id="myModal" class="modal fade" role="dialog">
        <div class="modal-dialog modal-lg">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Modal Header</h4>
                </div>
                <div class="modal-body">
                    <p>
                        <label for="start">Start: </label>
                        <input type="text" name="start" id="start" />
                        <label for="end">End: </label>
                        <input type="text" name="end" id="end" />
                        <input type="submit" value="Calculate Route" onclick="calcRoute()" />
                    </p>
                    <p>
                        <label for="distance">Distance (km): </label>
                        <input type="text" name="distance" id="distance" readonly="true" />
                        <input type="text" name="durationH" id="timeH" readonly="true" />
                        <input type="text" name="durationM" id="timeM" readonly="true" />
                    </p>
                </div>
                <div class="modal-body" id="map_canvas"></div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
        </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha256-KXn5puMvxCw+dAYznun+drMdG1IFl3agK0p/pqT9KAo= sha512-2e8qq0ETcfWRI4HJBzQiA3UoyFk6tbNyG+qSaIBZLyW9Xf3sWZHN/lxe9fTh1U45DpPf07yj94KsUHHWe4Yk1A==" crossorigin="anonymous"></script>

        <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
    <script>
        var directionDisplay;
        var map;
        initialize()    
        function initialize() {
            directionsDisplay = new google.maps.DirectionsRenderer();
            var melbourne = new google.maps.LatLng(51.6904085, 5.29543006);
            var myOptions = {
                zoom:12,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: melbourne
            }

            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            directionsDisplay.setMap(map);
        }

        var directionsService = new google.maps.DirectionsService();

        function calcRoute() {
            var start = document.getElementById("start").value;
            var end = document.getElementById("end").value;
            var distanceInput = document.getElementById("distance");
            var hours = document.getElementById("timeH");
            var minutes = document.getElementById("timeM");
//after click cacl call to google maps size reset
    google.maps.event.trigger(map, 'resize')
            var request = {
                origin:start,
                destination:end,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };

            directionsService.route(request, function(response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                    distanceInput.value = response.routes[0].legs[0].distance.value / 1000;

                    hours.value = parseInt( response.routes[0].legs[0].duration.value / 3600) % 24;
                    minutes.value = parseInt( response.routes[0].legs[0].duration.value / 60) % 60;
                    <!-- END Adding-->
                }
            });
        }
    </script>

答案 1 :(得分:1)

&#13;
&#13;
<!DOCTYPE html>
<html lang="en">
  <head>
  	<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

	<!-- Optional theme -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

	<!-- Latest compiled and minified JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
	<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  	<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="https://code.jquery.com/jquery.js"></script>
    <script src="http://maps.googleapis.com/maps/api/js"></script>
	
	<script type="text/javascript">
	  var map;
	  var markers = [];
	  var gLocation; //geo location of the customer
	  var labels ='Taxi';
	  var markerStart;
	  var markerEnd;
	  var directionsDisplay;
	  var directionsService = new google.maps.DirectionsService();
	   function initialize() {
	    directionsDisplay = new google.maps.DirectionsRenderer({
	    polylineOptions: {
	      strokeColor: "purple"
	    }
	  });
	    directionsDisplay.setMap(map);
	    var mapProp = {
	    center:new google.maps.LatLng(document.getElementById("startLat").value, document.getElementById("startLong").value),
	    zoom:12,
	    mapTypeId:google.maps.MapTypeId.ROADMAP
	    };
	    map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
	    var centerControlDiv = document.createElement('div');
	    centerControlDiv.index = 1;
	    centerControlDiv.style['padding-top'] = '10px';
	    map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);
	    var infowindowStart = new google.maps.InfoWindow({
	      content: 'Start'
	    });
	    var infowindowEnd = new google.maps.InfoWindow({
	      content: 'End'
	    });
	    markerStart = new google.maps.Marker({
	      position: new google.maps.LatLng(document.getElementById("startLat").value, document.getElementById("startLong").value),
	      map: map
	      });
	    markerStart.setVisible(false);
	    infowindowStart.open(map, markerStart);
	    markerEnd = new google.maps.Marker({
	      position: new google.maps.LatLng(document.getElementById("endLat").value, document.getElementById("endLong").value),
	      map: map
	      });
	    markerEnd.setVisible(false);
	      infowindowEnd.open(map, markerEnd);
	      markers.push(markerStart);
	      markers.push(markerEnd);
	      calcRoute(document.getElementById("startLat").value, document.getElementById("startLong").value,document.getElementById("endLat").value, document.getElementById("endLong").value);
	  }
	  function calcRoute(startLat,startLong,endLat,endLong) {
	        var start = new google.maps.LatLng(startLat, startLong);
	        var end = new google.maps.LatLng(endLat, endLong);
	        var bounds = new google.maps.LatLngBounds();
	        bounds.extend(start);
	        bounds.extend(end);
	        map.fitBounds(bounds);
	        var request = {
	            origin: start,
	            destination: end,
	            travelMode: google.maps.TravelMode.DRIVING
	        };
	        directionsService.route(request, function (response, status) {
	            if (status == google.maps.DirectionsStatus.OK) {
	                directionsDisplay.setDirections(response);
	                directionsDisplay.setMap(map);
	                var distance = response.routes[0].legs[0].distance.value;
	                var distanceKm = (distance/1000).toFixed(0);
	                var distanceM = (distance%1000).toFixed(0);
	                var duration = response.routes[0].legs[0].duration.value;
	                var durationHrs = (duration/3600).toFixed(0);
	                var durationMins = (duration%3600/60).toFixed(0);
	                document.getElementById('distance_duration').innerHTML ="Distance: "+distanceKm+"Km "+distanceM+"m. Duration: "+durationHrs+"Hrs "+durationMins+ "mins.";
	            } else {
	                alert("Directions Request from " + start.toUrlValue(6) + " to " + end.toUrlValue(6) + " failed: " + status);
	            }
	        });

	        
		 }
		  function sendData(startLat,startLong,endLat,endLong){
		    document.getElementById("startLat").value=String(startLat);
		    document.getElementById("startLong").value=String(startLong);
		    document.getElementById("endLat").value=String(endLat);
		    document.getElementById("endLong").value=String(endLong);
		    
		  }
</script>
  </head>
  <body>
    <div class="container" >
            <div class="jumbotron" style="background-color:white;">
                
                    <div class="panel panel-primary" >
                    <div class="panel-heading">My Hires</div>
							<table class="table table-condensed">
								<th>Tour ID</th>
								<th>Date</th>
								<th>Time</th>
								<th>Passenger Name</th>
								<th>Contact No</th>
								<th>No of Passengers</th>
								<th>Charges</th>
								<tr >
									<td>1</td>
									<td>02-03-2015</td>
									<td>01:12</td>
									<td>Bob</td>
									<td>+94789456225</td>
									<td>$1200</td>
									<td><a href="#" class="btn btn-sm btn-success" onclick="sendData('7.866383', '79.895345','7.912803', '80.798538');setTimeout(initialize, 500);" data-toggle="modal" data-target="#basicModal">Map</a></td>
								 </tr>
						</table>
                    </div>
                    <br>
                        </div>
                <!--Modal for map -->
                <div class="modal fade" id="basicModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
                  <div class="modal-dialog">
                    <div class="modal-content">
                      <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">close x</button>
                        <h4 class="modal-title" id="myModalLabel">Route for the request</h4>
                      </div>
                    <div class="modal-body">
                    <input type="hidden" id="startLat" name="test" value="initial" />
                    <input type="hidden" id="startLong" name="test1" value="initial" />
                    <input type="hidden" id="endLat" name="test2" value="initial" />
                    <input type="hidden" id="endLong" name="test3" value="initial" />
                    <pre id="distance_duration"></pre>
                    
                    
                    <div id="googleMap" style="width:500px;height:400px; margin:auto; border: 5px solid #73AD21; padding: 15px;"></div>
                    </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                      </div>
                    </div>
                  </div>
                </div>
                 <!--Modal end -->
              </div>
        </div>
    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="bootstrap.min.js"></script>
    <script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
    
  </body>
</html>
&#13;
&#13;
&#13;

希望这给了一个很好的理解。 您可以使用php使表格动态化并获取地图数据。