i’ve got some problem with JS code. When i make array with object my code work well, but whe i’m doing it in for() it’s doesnt work. This code work good
$(window).load(function () {
var map = new YMaps.Map(document.getElementById("YMapsID"));
map.setCenter(new YMaps.GeoPoint(37.64, 55.76), 10);
map.addControl(new locationSearchBox());
projects = [{Lat: "lat", Lng: "lng", Address: "address", label: "фывафыва"},
{Lat: "lat", Lng: "lng", Address: "address", label: "авыва"},
{Lat: "lat", Lng: "lng", Address: "address", label: "аваы"},
{Lat: "lat", Lng: "lng", Address: "address", label: "фываl"}];
console.log(projects);
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.label );
map.removeAllOverlays();
var point = new YMaps.GeoPoint(ui.item.Lng, ui.item.Lat);
var placemark = new YMaps.Placemark(point);
placemark.name = ui.item.label;
placemark.description = ui.item.Address;
map.addOverlay(placemark);
map.panTo(point, {flying: 1});
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
this one isn’t work =(
$(window).load(function () {
var map = new YMaps.Map(document.getElementById("YMapsID"));
map.setCenter(new YMaps.GeoPoint(37.64, 55.76), 10);
map.addControl(new locationSearchBox());
$.get("data.php",
function(data){
for (var i = 0; i < 4; i++) {
projects.push({Lat: data[i][0], label: data[i][1], Lng: data[i][3], Address: data[i][2]});
}
}, "json");
console.log(projects);
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.label );
map.removeAllOverlays();
var point = new YMaps.GeoPoint(ui.item.Lng, ui.item.Lat);
var placemark = new YMaps.Placemark(point);
placemark.name = ui.item.label;
placemark.description = ui.item.Address;
map.addOverlay(placemark);
map.panTo(point, {flying: 1});
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
Can anyone help me?
Thank you, Dima.
Ajax is asynchronous; that’s why you need to pass a separate function to
$.getand you can’t just dovar data = $.get(...).The response data will be available a while later because it has to be fetched over the network. In the meantime the rest of your code will execute, which is too early because that code relies on the response.
You will need to move all code that relies on the response data in that function passed to
$.get(the callback).