-1

I'm new to Google Maps, so please excuse me if the solution is obvious for experienced users, but I couldn't find any relevant information in the documentation.

I want to make a map of Egypt.

As much as I understand, I have to

  1. create a map with the "center" parameter at the center of the country -- LatLng(27.274553, 30.256790)

  2. ensure that the whole country is included in the map, i.e. define a zoom factor

By trials and errors, I found out that zoom:6 was the appropriate value in the <div> I use to display the map.

I'm wondering if there is a better way of computing the zoom factor, i.e. something like drawing a map including a rectangle provided by 2 points (NE, SW).

Thanks for your advice.

PapyJP
  • 1
  • 2
  • possible duplicate of [Google Maps V3 Geocode + Zoom](http://stackoverflow.com/questions/13689270/google-maps-v3-geocode-zoom) – geocodezip May 19 '16 at 19:09

1 Answers1

1

Use the Geocoder to determine the recommended viewport/bounds for your country of interest.

var geocoder, map, marker;

function codeAddress(address) {
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[0].geometry.viewport)
        map.fitBounds(results[0].geometry.viewport);
      else if (results[0].geometry.bounds)
        map.fitBounds(results[0].geometry.bounds);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

function initialize() {
  geocoder = new google.maps.Geocoder();
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  codeAddress("Egypt");

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • Thanks for your answer The code you provide shows a map centered on Egypt, but the scale is not the one I would like to have, and that's the subject of my question. In other terms: is there a way to have the zoom factor automatically computed so that the country is fully contained in the <div> but fills it as well as possible? – PapyJP May 20 '16 at 08:12
  • zoom levels in the google maps API are discrete. There is some padding, so it is possible you could zoom in one time and still see all or most of the country, but that is not guaranteed. – geocodezip May 20 '16 at 13:06
  • Thanks, ! I understand that the answer is "no, there is no way to do that". At least that makes things clear to me!! – PapyJP May 20 '16 at 16:46
  • In fact the answer is "Yes", you just have to enter the NE/SE points in a LatLngBounds object and run map.fitBounds() See http://stackoverflow.com/questions/2818984/google-map-api-v3-center-zoom-on-displayed-markers – PapyJP May 24 '16 at 08:08