я делаю ajax-вызов для извлечения данных json
я затем сохраняю восстановленные данные в ассоциативные массивы
, но когда я пытаюсь получить данные из ассоциативных массивов, ключи и значенияони не определены, я думаю, это потому, что данные сохраняются в виде значения [i], и когда цикл завершен, он больше не знает, что я, как мне исправить это?
может бытьвидно на этой странице http://www.focus -on-plants.com / locator_iconed.php вот мой сценарий
myUrl = 'geo_locator_icons.php';// url of php page that retrives the locations
// start a new ajax call
$.ajax({
type: "GET", //The type of HTTP verb (post, get, etc)
url: myUrl, //The URL from the form element where the AJAX request will be sent
dataType: 'json',
success: function(dat) { //Triggered after a successful response from server
var myData = dat.icons;
var count = myData.length - 1;
console.log(dat)
console.log(myData)
for(i=0; i < count; i++){
// Creating the icon
var icon_image = "'"+myData.folder_ico+myData.image_ico+"'" //set image
var icon_size = "new google.maps.Size"+myData.iconsize_ico //set size
var icon_origin = "new google.maps.Point(0, 0)" // The origin
var icon_anchor = "new google.maps.Point"+myData.iconanchor_ico //set anchorpoint
// Creating the shadow
var shadow_image = "'"+myData.folder_ico+myData.shadow_ico+"'" //set image
var shadow_size = "new google.maps.Size"+myData.shadowsize_ico //set size
var shadow_origin = null // The origin
var shadow_anchor = "new google.maps.Point"+myData.iconanchor_ico //set anchorpoint
// Creating the shape
var shape_type = 'poly'
var shape_coord = myData.imagemap_ico
// Creating the icon
var icon = new google.maps.MarkerImage(icon_image);
// Creating the shadow
var shadow = new google.maps.MarkerImage(
shadow_image,
shadow_size,
shadow_origin,
shadow_anchor
);
// Creating a shape
var shape = '{type: '+shape_type+', coord:'+shape_coord+'}'
// add the icon to the mapIconsArray
iconImageArray[myData.name_ico] = new google.maps.MarkerImage(
icon_image,
icon_size,
icon_origin,
icon_anchor
);
// add the icon to the shadowIconsArray
iconShadowArray[myData.name_ico] = new google.maps.MarkerImage(
shadow_image,
shadow_size,
shadow_origin,
shadow_anchor
);
// add the shape to the shapeIconsArray
iconShapeArray[myData.name_ico] = shape
};
},
error: function(dat) { //Triggered if an error communicating with server
$("#geo_detail").append('<label>There was an error retriving the Icons: '+dat+'<label><br>');
$('#loc_button').fadeIn('slow');
return 0;
},
});
console.log(iconImageArray)
console.log(iconShadowArray)
console.log(iconShapeArray)
<----------------------- обновление о том, что я пытаюсь достичь -------------------->
Функция createIcons()
будет запускаться при загрузке страницы после инициализации карты.
Я хочу, чтобы она сохраняла данные в 3 массивах (теперь объекты), которые я создал
var iconImageArray = {};
var iconShadowArray = {};
var iconShapeArray = {};
У меня есть функция с именем addMarkers()
, которая добавляет маркеры на карту. Я хочу иметь возможность изменять изображение маркера в зависимости от типа добавляемого маркера.
скрипт добавления маркера:
// ADD MARKER FUNCTION
// Adds a marker to the map
// PARAMS:
// @myLatrLng - latLng object
// @dat - Data containg location Info
function addMarker(map, myData){
// Create the marker
// create the marker info first
myLatLng = new google.maps.LatLng(myData.lat_mdt, myData.lng_mdt);
markersArray.push(myLatLng);
markersInfoArray.push(myData);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: myData.name_mdt,
icon: iconImageArray[myData.name_etp],
shadow: iconShadowArray[myData.name_etp],
shape: iconShapeArray[myData.name_etp],
});
// Wrapping the event listener inside an anonymous function
// that we immediately invoke and passes the variable i to.
(function(myData, marker) {
// Creating the event listener. It now has access to the values of
// myData and marker as they were during its creation
google.maps.event.addListener(marker, 'click', function() {
//create thecontent for the infowindow
var content = createContent(myData);
var infowindow = new google.maps.InfoWindow({
content: content
});
infowindow.open(map, marker);
});
})(myData, marker);
};
<---------------------- update ----------------------------------->
ну вот где я нахожусь, я провел множество испытаний сстатические данные и значки для карты генерируются нормально, поэтому мой реальный код карты Google в порядке и работает.
Как только я начинаю пытаться ссылаться на элементы из myIconsArray object
, все это ломается, и я не получаю консолисообщения, настроенные в addMarkers function
.
. Однако я замечаю, что когда я смотрю в консоли, структура myIcons Array
выглядит неправильно:
в myIconsArray у меня есть 3 объекта,icon {} shadow {}, shape {}
форма, кажется, в порядке, например: shape {orchid day {ordin {} type {}} stokist {ordin {} type {}
}
website visitor{
coord{}
type{}
}
}
но объекты изображений и теней имеют неправильные имена, например:
image {orchid day {Na {} // должен быть размера (значение правильное) anchor {} // shoule be anchorpoint (значение верное) b {} должно быть origin (значение верное) hb {} // shoне должно быть изображения (значение верное) hc {} не знаю, почему это здесь не определено и не используется мной !!!} stokist {ordin {} type {}
}
website visitor{
coord{}
type{}
}
}