2015-08-20 78 views
-1

我需要通過AJAX從文本文件獲取位置的經緯度,然後使用該信息創建地圖。這是我所做的:通過AJAX獲取位置信息後創建地圖

function createMap(){ 

var request; 

if (window.XMLHttpRequest) 
{ 
    request = new XMLHttpRequest(); 
} 

if (request) 
{ 
    var number = Math.floor((Math.random() * 3) + 1); 

    var url = "text_" + number + ".txt"; 

    request.open("GET", url,true); 

    request.onreadystatechange = function() 
    { 
     if (request.readyState == 4 && request.status == 200) 
     { 
     var syd=new google.maps.LatLng(-33.884183, 151.214944); 
     var woll=new google.maps.LatLng(request.responseText); 
     function initialize() 
     { 
      var mapProp = { 
        center:syd, 
        zoom:6, 
        mapTypeId:google.maps.MapTypeId.ROADMAP 
        }; 

      var map=new google.maps.Map(document.getElementById("outputAJAX"),mapProp); 

      var myTrip=[syd,woll]; 
      var flightPath=new google.maps.Polyline({ 
        path:myTrip, 
        strokeColor:"#0000FF", 
        strokeOpacity:0.8, 
        strokeWeight:2 
        }); 

      flightPath.setMap(map); 
     } 

      initialize(); 
     } 
    } 

    request.send(); 

} else { 

    document.getElementById("outputAJAX").innerHTML = "<span style='font-weight:bold;'>AJAX</span> is not supported by this browser!"; 
}} 

但是,地圖沒有顯示出來。你們有什麼建議嗎?

+0

什麼是'response.request.Text'? – geocodezip

+0

我有經度和3個不同的地方緯度這樣3個文本文件: '-31.946922,115.853511' '-34.424299,150.885959' '-37.854861,145.052150' – saimoon

回答

0

一個google.maps.LatLng object有兩個數字它的參數:

 
LatLng(lat:number, lng:number, noWrap?:boolean) Creates a LatLng object representing a geographic point. Latitude is specified in degrees within the range [-90, 90]. Longitude is specified in degrees within the range [-180, 180]. Set noWrap to true to enable values outside of this range. Note the ordering of latitude and longitude. 

這是不行的(你只是路過一個參數,一個字符串):

var woll=new google.maps.LatLng(request.responseText); 

假設request.responseText是逗號分隔的字符串包含兩個數值,這應該工作:

var coordStr = request.responseText; 
var coords = coordStr.split(","); 
var woll = new google.maps.LatLng(parseFloat(coords[0]), 
            parseFloat(coords[1])); 

proof of concept fiddle

+0

謝謝你,我想你所指出的一個問題。 但是,當我將它添加到我的代碼,它仍然沒有工作 我的問題是,它可以運行AJAX? – saimoon

+0

應該可以。你現在得到什麼錯誤?回調函數中的request.responseText的值是多少?你的HTML是什麼樣的? – geocodezip

+0

我沒有得到任何錯誤。我正在使用xampp並嘗試使用它運行我的代碼。和request.responseText的值是從文本文件所採取的字符串 – saimoon