2011-04-11 78 views
7

我試圖通過下一個示例http://jsbin.com/inepo3/7/edit獲取Google Maps API的lng和lat座標。我期望一個'成功'彈出窗口,但它一直顯示'錯誤'彈出窗口。 谷歌地圖 - 請求給出了正確的JSON反饋(由螢火蟲檢查)。通過ajax獲取Google Maps API的地址座標()請求

<script type="text/javascript"> 
    $().ready(function() { 

     $.fn.getCoordinates=function(address){ 

      $.ajax(
      { 
       type : "GET", 
       url: "http://maps.google.com/maps/api/geocode/json", 
       dataType: "jsonp", 
       data: { 
        address: address, 
        sensor: "true" 
       }, 
       success: function(data) { 
        set = data; 
        alert(set); 
       }, 
       error : function() { 
        alert("Error."); 
       } 
      }); 
     }; 

     $().getCoordinates("Amsterdam, Netherlands"); 
    }); 
</script> 

有誰知道如何解決這個問題?

問候, 圭多Lemmens

編輯

我發現使用谷歌地圖的JavaScript API結合jQuery的一個bether解決方案:

<script type="text/javascript"> 
    $().ready(function() { 
     var user1Location = "Amsterdam, Netherlands"; 
     var geocoder = new google.maps.Geocoder(); 
     //convert location into longitude and latitude 
     geocoder.geocode({ 
      address: user1Location 
     }, function(locResult) { 
      console.log(locResult); 
      var lat1 = locResult[0].geometry.location.lat(); 
      var lng1 = locResult[0].geometry.location.lng(); 
      $("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>"); 
     }); 
    }); 
</script> 
+0

谷歌地圖API的哪個版本? – kjy112 2011-04-11 15:32:40

+0

我不是舒爾,我猜v2(你可以將使用過的地圖網址轉換爲一個版本,也許?) – 2011-04-11 15:33:35

+0

我很確定它現在正在V3看着它。 – kjy112 2011-04-11 15:46:25

回答

9

谷歌地圖API V3就更難外部庫與JSONP一起工作。這是一篇關於它的博客文章。

JSONP and Google Maps API Geocoder Plus A Fix w/ jQuery


獲得地理編碼的另一種方法是使用Google Map V3 API Geocoder Service。這裏有一個例子,我幫助一個有類似問題的人替換他的JSONP來使用Google Map V3 Geocoder Service。看看這個JSFiddle Demo:

這基本上是核心。我們基本上使用Twitter來獲取鳴叫的地址(即倫敦,馬德里和格魯吉亞等),並使用谷歌地圖的地理編碼服務轉換的實際地址轉換成經緯度:

$.getJSON(
    url1, function(results) { // get the tweets 
     var res1 = results.results[0].text; 
     var user1name = results.results[0].from_user; 
     var user1Location = results.results[0].location; 

     // get the first tweet in the response and place it inside the div 
     $("#last-tweet1").html(res1 + "<p>from: " + user1name + " (" + user1Location + ")</p><p>"); 
     //convert location into longitude and latitude 
     geocoder.geocode({ 
      address: user1Location 
     }, function(locResult) { 
      console.log(locResult); 
      var lat1 = locResult[0].geometry.location.lat(); 
      var lng1 = locResult[0].geometry.location.lng(); 
      $("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>"); 
     }); 
    }); 
+1

酷,我只是制定了你的例子,並將其添加到我原來的帖子。這工作完美! – 2011-04-12 18:29:07

+0

非常有用,謝謝! – montrealist 2011-06-28 21:36:05

+0

得到crossdomain錯誤,爲什麼? – 2012-04-25 12:50:53

相關問題