JavaScript添加到数组并以html

时间:2016-11-15 12:31:10

标签: javascript arrays geocoding

我正在处理来自Google的一段代码,试图对其进行更改,以便代替windows.alerting LT / LN坐标,将坐标保存在一个数组中,然后可以在一个表中显示某种。

function geocodeAddress(geocoder, resultsMap) {
    var cords = []; //my array
    var address = document.getElementById('address').value;
    geocoder.geocode({'address': address}, function(results, status) {
      if (status === 'OK') {
        window.alert("Coordinates:" + results[0].geometry.location); //current alert           
        cords.push(results[0].geometry.location); //adding to an Array            
      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
  }

我对JS非常生疏,所以我甚至不确定它是否存储在Array中。我尝试了多种方法将数组显示到屏幕上,但没有任何效果,我不确定是否因为没有存储在数组中,或者因为我没有正确显示数组。

明确提出:关于如何在数组和数组中存储这些坐标的任何想法我应该如何在屏幕上显示这个数组?欢呼声。

2 个答案:

答案 0 :(得分:0)

如果要在HTML中显示数组:

HTML:

<div data-cords></div>

JS:

var html = '';
cords.forEach(function(cord) {
   html += cord + '<br>';
});
document.querySelector('[data-cords]').innerHTML = html;

否则,您可以在开发者控制台中打印数组:

console.log(cords);

或者,如果你想alert,你可以使用与上面相同的结构:

var alertMessage = '';
cords.forEach(function(cord) {
   alertMessage += cord + '\n'; // new line character
});
alert(alertMessage);

答案 1 :(得分:0)

我希望这会对你有所帮助。

&#13;
&#13;
var cords = [];
function searchAddress() {
  var addressInput = document.getElementById('address-input').value;
  document.getElementById('address-input').value = "";

  var geocoder = new google.maps.Geocoder();

  geocoder.geocode({address: addressInput}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {

      var myResult = results[0].geometry.location; // reference LatLng value
      
      cords.push(myResult);
      
        document.getElementById('add-loc').appendChild(generateList(cords));
      
    } else { 
    // warning message
    alert("The Geocode was not successful for the following reason: " + status);

  }
 });

}

function generateList(array) {
    // Create the list element:
    var list = document.createElement('ul');

    for(var i = 0; i < array.length; i++) {
        // Create the list item:
        var item = document.createElement('li');

        // Set its contents:
        item.appendChild(document.createTextNode(array[i]));

        // Add it to the list:
        list.appendChild(item);
    }

    // Finally, return the constructed list:
    return list;
}
&#13;
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
  
<body>
    <div>
       Enter address <input type="text" id="address-input">
       <button onclick="searchAddress();">Search</button>
    </div>   
    <div id="add-loc"></div>
  </body>
&#13;
&#13;
&#13;