How to center a google map nationwide if you just have a country name

I have a page about hiking in different countries. I’m trying to make such a page for each country, but I don’t know how to automatically center the Google map throughout the country, and also adjust it depending on the size of the country.

Here are my problematic pages:

http://www.comehike.com/outdoors/country.php?country_id=6&country_name=Belarus

http://www.comehike.com/outdoors/country.php?country_id=1&country_name=United%20States

Do you see how the size of centering and focusing is static? This is because I am currently using this code to center the map:

function initialize( ) { var myLatlng = new google.maps.LatLng(37.775, -122.4183333); var myOptions = { zoom: 2, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); } 

But this is only because I'm not sure how to do this by the name of the country, and automatically adjust the size. How to do this by passing the country name to the initialization function?

Thanks!

+6
source share
1 answer

You can convert the country name to coordinates using the Geocoding Service . The example provided by Google centers is a map, but does not enlarge it. To zoom in, you should use the map.fitBounds () method using the LatLngBounds object returned by the geocoder. This is a sample code:

 var myLatlng = new google.maps.LatLng(37.775, -122.4183333); var myOptions = { zoom: 2, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var address = "Belarus"; var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); map.fitBounds(results[0].geometry.bounds); } else { alert("Geocode was not successful for the following reason: " + status); } }); 
+11
source

Source: https://habr.com/ru/post/888742/


All Articles