Answer the question
In order to leave comments, you need to log in
How to pass data from php file to javascript variable?
Through the API I receive data from a third-party service. Response structure:
[ {
...
“Latitude”: “<Широта>”,
“Longitude”: “<Долгота>”,
...
} ]
foreach ($response as $item) {
$a = "[".$item['Latitude'].",".$item['Longitude']."]," ;
$array = $array.$a ;
}
$list= substr($array, 0, -1);
echo json_encode($list);
var myMap = new ymaps.Map('map', {
...
points = [
[55.831903,37.411961], [55.763338,37.565466]
],
}
function showData() {
var data="";
$.ajax({
url: "/GetList.php",
data: "",
dataType: 'json',
success: function(response) {
var data = response;
}
});
return data;
}
...
var myMap = new ymaps.Map('map', {
...
points = [
data
],
}
Answer the question
In order to leave comments, you need to log in
So build the map right away in the success block of the ajax request.
I did not work with Yandex, but on the example of Google (from one working project). I received the data, and I immediately work with them.
$.ajax({
url: "coords.json",
dataType: "json",
async: true,
success: function(msg){
google.maps.event.addDomListener(window, 'load', init);
function init() {
var mapOptions = {
zoom: 2,
center: new google.maps.LatLng(42, 10),
scrollwheel: false
};
var mapElement = document.getElementById('map');
var map = new google.maps.Map(mapElement, mapOptions);
setMarkers(map);
map.addListener('click', function() {
if (infowindow) {
infowindow.close();
}
});
}
function setMarkers(map) {
for (var n = 0; n < msg.length; n++) {
console.group('Path: '+n);
for (var i = 0; i < msg[n].length; i++) {
var m = i+1;
var mrk = msg[n][i];
var next_mrk = msg[n][m];
var marker = new google.maps.Marker({
position: {lat: mrk[1], lng: mrk[2]},
map: map,
icon: image,
title: mrk[0],
});
Message(marker, mrk[3]);
if(next_mrk) {
var dashedLine = new google.maps.Polyline({
path: [
{lat: mrk[1], lng: mrk[2]},
{lat: next_mrk[1], lng: next_mrk[2]}
],
strokeOpacity: 0,
icons: [{
icon: line,
offset: '0',
repeat: '6px'
}],
map: map
});
console.dirxml(mrk[0]+" - "+next_mrk[0]);
} else {
console.dirxml(msg[n][i][0]);
}
}
console.groupEnd();
}
}
function Message(marker, msg) {
var infowindow = new google.maps.InfoWindow({
content: msg
});
marker.addListener('mouseover', function() {
this.setIcon(image_hover); this.setZIndex(2);
infowindow.open(marker.get('map'), marker);
});
marker.addListener('mouseout', function() {
this.setIcon(image); this.setZIndex(1);
infowindow.close();
});
marker.addListener('click', function() {
marker.get('map').setZoom(6);
marker.get('map').setCenter(marker.getPosition());
});
}
}
});
or for example in the date attribute, like:
<body data-you-var-from-php='{"x": 1000, "y": 2000}'>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question