简体   繁体   中英

How to make google map responsive inside any div element?

I have a problem using responsive Google map on my page. I am using Google Map API v3 & bootstrap 3 CSS to make my site mobile first & responsive. I intend to get users address either by using Google places API by automatically filling up the address form or by getting coordinates from the map and GPS. I am using radio button to enable user to select either of the two options. The address form is selected as default option. When Use Map option is selected, the form has to be hidden & the Google map should be visible in its place but that just won't happen. I used Mozilla's Inspect Element option to check if the map is loaded in the background & yes it did.

The problem: The map just wont show up on the specified div which is div id="map-canvas" Except that everything works fine, I even managed to get static Google map as image to be displayed in the same div appending the image file to the div using .innerHTML() function.

The solution I need ia to be able to display the map inside the map-canvas div & the map should be responsive.

Here's my code (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>

Adding class col-xs-12 to your map div will do the job.

Go ahead re-size the windows, the map will automatically resize, remaining in its div.

 .yourdiv { border: solid; } 
 <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> 

Hope this you looking for.. which i understand from your question. Define 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM