如何让谷歌地图在任何div元素内响应?

时间:2015-05-12 12:04:25

标签: javascript html css google-maps

我在网页上使用自适应Google地图时遇到问题。我正在使用Google Map API v3& bootstrap 3 CSS使我的网站首先移动&响应。我打算通过自动填写地址表单或从地图和GPS获取坐标来使用Google Places API来解决用户问题。 我使用单选按钮使用户可以选择两个选项之一。地址表单被选为默认选项。选择“使用地图”选项后,表格必须隐藏。 Google地图应该在其位置可见,但这不会发生。我使用了Mozilla的Inspect Element选项来检查地图是否已加载到后台&是的,确实如此。

问题: 地图只是不会出现在指定的div上,即div id =“map-canvas”除了一切正常,我甚至设法获得静态Google地图作为图像显示在相同的div中,将图像文件附加到div使用.innerHTML()函数。

我需要的解决方案ia能够在map-canvas div&中显示地图。地图应该响应。

这是我的代码(html + js + css):

<!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">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Address form</title>

    <!-- Bootstrap Core CSS -->
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">

   <!--Start of CSS for Google Places API-->     
    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">

    <style>
      #locationField{
        position: relative;
      }
    </style>
    <!--End of assets for G Places API-->

    <!-- jQuery -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>


<body  onload="initialize()">
    <div class="container">
        <div>
            <legend>Address</legend>
        </div>
        <form class="form-horizontal" action="" method="POST">
                    <fieldset>
                        <div class="well col-md-12">
                            <h4><strong>Where are you?</strong></h4><br /><br />
                            <legend></legend>


                            <div class="col-md-6">
                                <h4><strong>Your Information</strong></h4>
                                <legend></legend>

                                <div class="control-group">
                            <label class="control-label" for="location">Provide your location:</label>
                            <div class="controls">
                                <label class="radio-inline"><input id="loc_method" type="radio" name="loc_method" value="form" class="input-xlarge" checked required>Use Form &nbsp;</label>
                                <label class="radio-inline"><input id="loc_method" type="radio" name="loc_method" value="map" class="input-xlarge" onClick="getLocation()" required>Use Map &nbsp;&nbsp;</label>
                                 <br />
                            </div>
                        </div>

                                <div class="address-form">

                                    <div class="control-group">
                                        <label class="control-label" for="address">Address</label>
                                        <div class="controls">
                                        <div id="locationField">
                                            <input type="text" id="autocomplete" name="address" placeholder="Enter your address" class="form-control" required>
                                        </div>
                                        </div>
                                    </div>
                                    <br />
                                    <div class="control-group">
                                        <table class="table table-bordered table-hover">
                                    <tr>
            <td><label class="control-label">Locality</label></td>
            <td><input class="form-control" id="street_number" name="tole" disabled="true"></input></td>
            </tr>
            <tr>
            <td><label class="control-label">Street</label></td>
            <td><input class="form-control" name="street" id="route" disabled="true"></input></td>
          </tr>
          <tr>
            <td><label class="control-label">City</label></td>
            <td><input class="form-control" id="locality" name="city_vdc" disabled="true"></input></td>
          </tr>
          <tr>
            <td><label class="control-label">Region</label></td>
            <td><input class="form-control" name="region" id="administrative_area_level_1" disabled="true"></input></td>
          </tr>
          <tr>
            <td><label class="control-label">Zip code</label></td>
            <td><input class="form-control" id="postal_code" name="zip" disabled=""></input></td>
          </tr>
          <tr>
            <td><label class="control-label">Country</label></td>
            <td><input class="form-control" name="country" id="country" disabled="true"></input></td>
          </tr>

                                    </table>
                                    </div>

                                </div>

                                <div class="map-canvas control-group">
                                    <div id="map-canvas">
                                <!--Map Should Be Here-->
                                    </div>
                                </div>

                            </div>



                            <!-- Button -->
                            <div class="control-group col-md-12">
                                 <br /><legend></legend>
                                <div class="controls">
                                    <button type="submit" name="submit" class="btn btn-success pull-right">Submit</button>
                                    <br /><br />
                                </div>
                            </div>
                        </div>
                    </fieldset>
                </form>
    </div>

<!--JS for Address Mode Selection-->
<script type="text/javascript">
$("input:radio[name=loc_method]:first-child").click(function(){
    if($(this).val()=="form"){
        $(".address-form").css("display","block");
        $(".map-canvas").css("display","none")
    }else{
        $(".map-canvas").css("display","block");
        $(".address-form").css("display","none");
    }
})

</script>

<!--JS API For Google Places Address Form Autofill-->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>

<script type="text/javascript">
var y = document.getElementById("map-canvas");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition,  showError,{
        enableHighAccuracy: true,
        timeout:30000
        });
    } else { 
        y.innerHTML = "Geolocation is not supported by this browser, choose <b>Use Form</b> option to fill the address form.";
    }
}

function showPosition(position) {
//These commented codes below are to display static GMap of the acquired coordinates as image in the div id="map-canvas" which I did successfully
    /*var latlon = position.coords.latitude + "," + position.coords.longitude;

    var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
    +latlon+"&zoom=14&size=320x240&sensor=true";

    y.innerHTML = "<br />Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude + 
    "<br>Altitude: " + position.coords.altitude + 
    "<br>Position Accuracy: " + position.coords.accuracy + 
    "<br>AltitudeAccuracy: " + position.coords.altitudeAccuracy +
    "<br><img src='"+img_url+"'>";*/

    var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    var myOptions = {
    zoom: 14,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.HYBRID
    };
    var map = new google.maps.Map(document.getElementById("map-canvas"),myOptions);
    //google.maps.event.addDomListener(window, 'load', initialize);
    var point = new google.maps.LatLng(position.coords.atitude, position.coords.longitude);
    var marker = new google.maps.Marker({
        position:point,
        map:map,
        title:'Rescue Team Needed Here @ <br />' + position.coords.latitude + 'deg. South & <br />' + position.coords.longitude + 'deg. East',
        draggable:true,
    });

}

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation. If you are concerned with your privacy choose <b>Use Form</b> option to fill the address form."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable. Choose <b>Use Form</b> option to fill the address form."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out. Choose <b>Use Form</b> option to fill the address form."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred. Choose <b>Use Form</b> option to fill the address form."
            break;
    }
}

</script>

<script>
var placeSearch, autocomplete;
var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_name'
};

function initialize() {
  // Create the autocomplete object, restricting the search
  // to geographical location types.
  autocomplete = new google.maps.places.Autocomplete(
      /** @type {HTMLInputElement} */(document.getElementById('autocomplete')),
      { types: ['geocode'],
      componentRestrictions: {country: 'np'}});
  // When the user selects an address from the dropdown,
  // populate the address fields in the form.
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
    fillInAddress();
  });
}

// [START region_fillform]
function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}
// [END region_fillform]

// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = new google.maps.LatLng(
          position.coords.latitude, position.coords.longitude);
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
// [END region_geolocation]

    </script>

2 个答案:

答案 0 :(得分:2)

将地图col-xs-12添加到地图div即可完成任务。

继续重新调整窗口大小,地图会自动调整大小,保留在div中。

&#13;
&#13;
.yourdiv {
  border: solid;
}
&#13;
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

<!DOCTYPE html>
<html>

<head>
  <title>Simple Map</title>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">
  <style>
    html,
    body,
    #map-canvas {
      height: 100%;
      margin: 0px;
      padding: 0px
    }
  </style>
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
  <script>
    var map;

    function initialize() {
      var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(-34.397, 150.644)
      };
      map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);
    }

    google.maps.event.addDomListener(window, 'load', initialize);
  </script>
</head>

<body>
  <div class="yourdiv col-xs-12" id="map-canvas"></div>
</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

希望你找到..我从你的问题中理解。 定义width:100%

#map-canvas {
  margin: 20px 0;
  padding: 0;
  height: 300px;
  float: left;
  width: 100%;
}

HTML CODE

<div class="col-md-12">
<div id="map-canvas" style="position: relative; overflow: hidden; transform: translateZ(0px); background-color: rgb(229, 227, 223);"></div>
</div>