利用 Google Map API 把地址轉換成經緯度

先載入 jQuery / GoogleMap API



HTML 如下:

輸入地址

地址轉換經緯度結果 (格式:Latitude,Longitude)

JavaScript 如下:

$(function () {
   var i;
   var split, address;

   $(“#source").blur(function () {
      i = 0;
      $(“#target").val(“");
      var content = $(“#source").val();
      split = content.split(“\n");
      transLoop();
   });

   function transLoop() {
      address = split[i].split(“,");
      addressToLngLat(address[2]);
      if (++i == split.length) {
         return;
      }
      setTimeout(transLoop, 1500);
   }

   function addressToLngLat(addr) {
      var geocoder = new google.maps.Geocoder();
      geocoder.geocode({
         “address": addr
      }, function (results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
            var txtJson = “{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[“;
            txtJson += results[0].geometry.location.lng() + “," + results[0].geometry.location.lat() + “]},";
            txtJson += “\"properties\":{“;
            txtJson += “\"name\":\"" + address[0] + “\",";
            txtJson += “\"tel\":\"" + address[1] + “\",";
            txtJson += “\"address\":\"" + address[2] + “\"}},";
            $(“#target").val($(“#target").val() + txtJson + “\n");
         } else {
            $(“#target").val($(“#target").val() + address[0] + “\n");
         }
      });
   }
});

輸入地址格式如下:
地址可輸入多筆,一筆一行,但建議不要太多筆( < 10 ),GoogleMap API 會擋掉。

流線傳媒股份有限公司,02-8771-5865,台北市光復南路102號14樓

產出的 JSON 字串如下:

{
“type":"Feature",
“geometry":{“type":"Point","coordinates":[121.55748960000005,25.0435228]},
“properties":{“name":"流線傳媒股份有限公司","tel":"02-8771-5865″,"address":"台北市光復南路102號14樓"}
},