如何使用Google地图将地址转换为经纬度

3
我希望能够在谷歌地图上标注几个公司,并且我知道需要进行地理编码。
下面是可以在地图上标注多个标记的代码。
我该如何将几个公司的地址(以下地址为第一个示例)进行地理编码,并将其合并到我已有的代码中?
我真的需要某人的帮助,因为我无法理解Google的文档,也无法将其与我已有的内容结合起来。
1个回答

8
你可以使用Google的地理编码来获取您的邮政编码的坐标。
编辑:我不太喜欢你改变问题的意思,但没关系。请尝试类似这样的东西(没有测试过):
// Creating an array that will contain the coordinates 
// for New York, San Francisco, and Seattle
var places = [];

// Adding a LatLng object for each city
//places.push(new google.maps.LatLng(40.756, -73.986));
//places.push(new google.maps.LatLng(37.775, -122.419));
//places.push(new google.maps.LatLng(47.620, -122.347));
//places.push(new google.maps.LatLng(-22.933, -43.184));
var result;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?address=your+code&sensor=false",true);
 xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4) {
       result = eval('(' + xmlhttp.responseText + ')');
if (result.status == "OK") {
var location = new google.maps.LatLng(result.results[0].geometry.location.lat, result.results[0].geometry.location.lng);
places.push(location);

这应该能够正常工作,尽管可能存在一些小错误。
编辑2:我刚刚找到了更简单的解决方案
// Creating an array that will contain the coordinates 
// for New York, San Francisco, and Seattle
var places = [];

// Adding a LatLng object for each city
//places.push(new google.maps.LatLng(40.756, -73.986));
//places.push(new google.maps.LatLng(37.775, -122.419));
//places.push(new google.maps.LatLng(47.620, -122.347));
//places.push(new google.maps.LatLng(-22.933, -43.184));
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "your+code"}, 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
    //});
    places.push(results[0].geometry.location);
  } else {
    alert("Geocode was not successful for the following reason: " + status);
  }
});

谢谢,我不知道从哪里开始处理它,更别说将其与我目前的代码合并了。 - Rob
1
看看我提供的链接网站: http://www.w3schools.com/xml/xml_http.asp ,只需像这样构建您的请求: http://maps.googleapis.com/maps/api/geocode/json?address=SW1A+0AA 评估谷歌的JSON响应,你就可以开始了。 - slawekwin
1
哎呀,我忘记在地理编码请求中加入传感器了:maps.googleapis.com/maps/api/geocode/json?address=SW1A+0AA&sensor=false - slawekwin
谢谢您的编辑。那应该放在我的当前代码哪里? - Rob
你应该将这些结果放在代表经纬度对象的硬编码数组中,我会再次编辑答案以更清晰地展示它。 - slawekwin
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接