我试图让控制台显示 id 以及纬度和经度,理想情况下,这是将其保存在一个数组中,然后我可以将其存储到 mysql 数据库中。这涉及到谷歌地图Javascript API的使用。
这是代码:
<script>
var markers;
function initMap() {
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
// this connects to the database
function geocodeAddress(geocoder, resultsMap) {
downloadUrl('maps.php', function(data) {
// var cdata = JSON.parse(document.getElementById('data').innerHTML);
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('type');
var lat = markerElem.getAttribute('lat');
var lng = markerElem.getAttribute('lng');
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
lat = (results[0].geometry.location.lat());
lng = (results[0].geometry.location.lng());
var points = {};
points.id = id.id;
points.lat = map.getCenter().lat();
points.lng = map.getCenter().lng();
getlatlng(points);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
})
});
});
function getlatlng(points) {
console.log(points);
}
}
geocodeAddress(geocoder, map);
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
}
function doNothing() {}
</script>
加载控制台后,id
将显示为未定义,而 lat
和 lng
将显示。有人可以帮我解决这个问题吗?
最佳答案
可能是因为 var id =markerElem.getAttribute('id');
不返回数组,而这里 points.id = id.id;
你攻击了属性“id”。将其更改为 points.id = id;
应该可以解决问题。
关于javascript - 为什么控制台不能定义id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50211327/