如何通过country_name在谷歌地图api上显示标记

时间:2014-06-30 11:13:43

标签: javascript google-maps google-maps-api-3

for(var x in recipient_country){
    var building = recipient_country[x];
    var location = new google.maps.LatLng(building.Country_Name)
    var marker = new MarkerWithLabel({
        position:location,
        title:building.Value,
        map:map,
        labelContent:building.Value,
        labelAnchor: new google.maps.Point(6,22),
        labelClass: "labels", // the CSS class for the label
        labelInBackground: false,
        icon:"circle2.png"
    });
}

我有以下json格式数据

var recipient_country = [
  {"Country_Name": "MYANMAR", "value": 143},
  {"Country_Name": "MONGOLIA", "value": 46},
  {"Country_Name": "ZIMBABWE", "value": 1},
  {"Country_Name": "Bahrain", "value": 1}
];

当我拨打Country_name时,通过从数据访问Country_name,我无法在地图上看到google标记。如何通过访问Country_name而不是其纬度和经度将标记放在谷歌地图上。

2 个答案:

答案 0 :(得分:2)

您可以使用Google Geocoder

尝试:

geocoder = new google.maps.Geocoder();

for(var x in recipient_country){
     var building = recipient_country[x];

     geocoder.geocode( { 'address': building.Country_Name}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var marker = new MarkerWithLabel({
            position:results[0].geometry.location,
            title:building.Value,
            map:map,
            labelContent:building.Value,
            labelAnchor: new google.maps.Point(6,22),
            labelClass: "labels", // the CSS class for the label
            labelInBackground: false,
            icon:"circle2.png"
    });
           });
        } else {
          console.log("Geocode was not successful for the following reason: " + status);
        }
    });


}

答案 1 :(得分:1)

您应该使用地理编码来查找国家/地区的Lat / Lng。

This sample from Google可以帮到你。

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

function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode( { 'address': address}, 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);
    }
  });
}