我遇到了jQuery或Javascript的问题。我试图从IP阵列中显示谷歌地图中的更多标志。我设法传递给IP数组的函数,但是当我使用ajax调用web api时,我有一个问题,就像数组长度一样,结果 locations 数组为空(未定);
这是我的代码
Object.finalize()
答案 0 :(得分:0)
你的意思是
locations[i] = location;
而不是
locations[i] = data;
您可能有上下文,范围问题。使用回调时,回调函数无法查看初始化调用创建的值。最快的解决方案是定义初始化之外的位置。
答案 1 :(得分:0)
这是完全未经测试的,但更多的是这些方面。我将地图设为全局变量。
var map = null;
function initialize(ipList) {
var ips = ipList;
var apiUrl = 'http://freegeoip.net/json/';
$.each(ips, function (i, x) {
$.ajax
({
url: apiUrl + x,
type: "POST",
cache: false,
success: function (data) {
if (data != null) {
porcessPoint(data);
}
}
});
});
}
function processPoint(datapoint) {
// assuming the first point is used to create the map
if (!map) {
var properties =
{
center: new google.maps.LatLng(datapoint.latitude, datapoint.longitude),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), properties);
}
var marker = new google.maps.Marker
({
position: { lat: datapoint.latitude, lng: datapoint.longitude },
animation: google.maps.Animation.BOUNCE,
title: datapoint.city
});
marker.setMap(map);
}
答案 2 :(得分:0)
我希望这对某人有用。这就是我改变整个代码的方式:
$(function()
{
$('#details').hide();
$("#btnSubmit").click(function()
{
var ipInput = $("#ipInput").val();
$.ajax
({
type: 'post',
url: 'http://localhost/LocationFromIP/public_html/php/traceroute.php',
data: {param: ipInput},
success: function(data)
{
var ipList = data.match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g);
for(var i = 0; i < ipList.length; i++)
{
$('#details').append(ipList[i] + '<br />');
}
initialize(ipList);
$('#details').show();
},
error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(thrownError);
}
});
});
});
function initialize(ipList)
{
var ips = ipList;
var apiUrl = 'http://freegeoip.net/json/';
var map = null;
$.each(ips, function(i, x)
{
$.ajax
({
url: apiUrl + x,
type: "GET",
cache: false,
success: function(location)
{
if (i == 0)
{
var properties =
{
center: new google.maps.LatLng(location.latitude, location.longitude),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"),properties);
}
var marker = new google.maps.Marker
({
position:{lat: location.latitude, lng: location.longitude},
animation:google.maps.Animation.BOUNCE,
title: location.city
});
marker.setMap(map);
}
});
});
}