2013-09-27 2 views
0

거리 주소를 좌표로 변환하는 자바 스크립트가 있습니다. 하지만 나는 사용자가 입력 필드의 주소를 입력 할 때 javascript를이를 lat 및 lng로 변환하고 입력 필드 아래에 p div에 결과를 넣기를 원합니다.거리 주소를 좌표로 변환하고 html로 배치하십시오.

내가 가진 JS 코드는 사전에

var latitude; 
    var longitude; 

    /* 
    * Get the json file from Google Geo 
    */ 
    function Convert_LatLng_To_Address(address, callback) { 
      url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=false"; 
      jQuery.getJSON(url, function (json) { 
       Create_Address(json, callback); 
      });   
    } 

    /* 
    * Create an address out of the json  
    */ 
    function Create_Address(json, callback) { 
     if (!check_status(json)) // If the json file's status is not ok, then return 
      return 0; 
     latitude = json["results"][0]["geometry"]["location"]["lat"]; 
     longitude = json["results"][0]["geometry"]["location"]["lng"]; 
     callback(); 
    } 

    /* 
    * Check if the json data from Google Geo is valid 
    */ 
    function check_status(json) { 
     if (json["status"] == "OK") return true; 
     return false; 
    } 
     <body> 
     Address: 
    <input type="text" id="address-input"> 
    City: 
    <input type="text" id="city-input"> 
    Country: 
    <input type="text" id="country-input"> 
    Postcode: 
    <input type="text" id="address4"> 
    <input type="submit" id="submit" value="generate" onClick="AlertLatLng()"> 


    <p id="result"></p> 




    <script> 

var street_address = document.getElementById('address-input').value, 
    city = document.getElementById('city-input').value, 
    country = document.getElementById('country-input').value, 
    postcode = document.getElementById('postcode-input').value; 

var address = street_address + ' ' + city + ' ' + country + ', ' + postcode; 

     // AlertLatLng is a callback function which will be executed after converting   address to coordinates 
     Convert_LatLng_To_Address(address, AlertLatLng);  

     /* 
     * Alert Latitude & Longitude 
     */ 
     function AlertLatLng() { 
    var result = "The latitude is " + latitude + " and longitude is " + longitude; 
    document.getElementById('result').innerHTML=result; 
} 
</scrip> 
    </body> 

감사합니다 :)

답변

0

당신은 DOM 요소의 내용을 설정 javacsript를 사용할 수 있습니다.

에 javscript :

function AlertLatLng() { 
    var result = "The latitude is " + latitude + " and longitude is " + longitude; 
    document.getElementById('result').innerHTML=result; 
} 

이 이제 입력 필드 아래에있는 <p id='result'> 태그에 당신의 메시지를 배치하는 것입니다.

편집 :

당신이 입력 필드의 값을 잡기 위해 필요한 자바 스크립트로 폼 입력 필드에서 정보를 전달하려면 (참조 : Passing HTML Form Data to Javascript Function을). 한마디로 :

var address = "address+city+country,+postcode" 

될 수 있을까 : 그것은 당신의 코드를 쉽게 만들 수 있습니다 id="city-input", id="postcode-input" 등 :

var street_address = document.getElementById('address1').value, 
    city = document.getElementById('address2').value, 
    country = document.getElementById('address3').value, 
    postcode = document.getElementById('address4').value; 
var address = street_address + ' ' + city + ' ' + country + ', ' + postcode; 

제안으로 당신이 당신의 입력 태그를보다 직관적 id 속성을 사용할 수 있습니다 독서.

편집 2 : 빠른 측면으로

은 코드 하단의 닫는 태그에 스크립트 철자가 note..you. 브라우저가이 문제를 해결할 가능성이 높지만 처리하는 데 가치가있을 수 있습니다. 그것은에 호출을 Convert_LatLng_To_AddressjQuery.getJSON 호출에 대한 콜백 함수입니다 Create_Address에 정의 얻을 위도와 경도 변수처럼 나에게 보이는

질문의 다음 부분에 관해서는

... Google지도 api.

변수 address을 설정하는 하단의 js 코드는 페이지로드시 한 번만 실행됩니다. 결과는 모든 변수가 빈 문자열이거나 정의되지 않을 것입니다. Convert_LatLng_To_Address(address, AlertLatLng) 번으로 전화를 걸면 괜찮습니다. 단, 양식에 정보가 있으면이 문제가 발생할 수 있습니다.

양식의 제출 조치는 클릭 이벤트에 AlertLatLng()을 호출합니다. Google지도 API에 새로 전화를 걸려면 입력 필드에 한 번만 입력하는 대신 정보를 입력해야합니다.

나는 그런

function getNewLatLng() { 
    var street_address = document.getElementById('address-input').value, 
    city = document.getElementById('city-input').value, 
    country = document.getElementById('country-input').value, 
    postcode = document.getElementById('postcode-input').value; 

    var address = street_address + ' ' + city + ' ' + country + ', ' + postcode; 

    // AlertLatLng is a callback function which will be executed after converting address to coordinates 
    Convert_LatLng_To_Address(address, AlertLatLng); 
} 

같은 간단한 함수에 모든 코드를 포장 한 후 제출 대신이 기능을 실행하기 위해 HTML을 편집 제안 :

<input type="submit" id="submit" value="generate" onClick="getNewLatLng()"> 
+0

위 코드를 편집하여 p 태그에 결과를 표시합니다. 사용자가 입력하는 입력 필드에서 정보를 얻기 위해 주소 변수에 무엇을 넣어야합니까? –

+0

답변을 편집하여 여기에 포함시켜 드리겠습니다 ... –

+0

질문에 대한 답변을 했습니까? 도움을 주신 덕분에 –

0

이미 jQuery를 가지고 로드 할 수 있습니다 :

function AlertLatLng() { 
    $("p#result").text("The latitude is " + latitude + " and longitude is " + longitude); 
} 

사이드 노트로, 당신은 위도와 경도는 Create_Address의 콜백 번호()에 표시됩니다.