简体   繁体   中英

Google Maps API, place markers on countries without using coordinates

I am using the Google Maps API and currently successfully adding markers based on exact locations, but I would like to also be able to add markers over countries without needing to have the coordinates of that country.

Is this possible?

It is highly possible indeed. Use GeoCoder : https://developers.google.com/maps/documentation/javascript/geocoding

GeoCoder can return the lat / lngs for a country, just by knowing its name.

Assuming you already have a map :

geocoder = new google.maps.Geocoder();

function getCountry(country) {
    geocoder.geocode( { 'address': country }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
           map.setCenter(results[0].geometry.location);
           var marker = new google.maps.Marker({
               map: map,
               position: results[0].geometry.location
           });
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

getCountry('USA');
getCountry('Brazil');
getCountry('Denmark');

Will place markers on your map in the direct center of USA, Brazil and Denmark.

在此输入图像描述

According to the Maps API, marker.position is a required property, and it must be of LatLng type. So at the very least you'd either need to know the coordinates at the centre of the country, or an bounded array of coordinates for the country from which you you can extrapolate the coordinates for the centre.

I believe that if you use the Geocoder with just the country name, the service will provide you with the coordinates for the exact centre of the country. I've not tested this, and I don't know what if there's a limit to how much you can use it, but it would be worth you checking it out as a solution to your question.

For example:

var geo = new google.maps.Geocoder();
geo.geocoder.geocode('Spain', function (data) {
  // the coordinates are held in data[0].geometry.location.lat() and data[0].geometry.location.lng().
});

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