I have index.php and ajax.php. When the page loaded ajax function returning a json data from ajax.php. Ajax.php is working. I can get json data. The map is loading firstly than ajax function so I get variable json is not defined error. İf I use json data result directly. For example var json=[{{"id":48,"title":"a","lng":"28.6643180847168","lat":"41.0327529907227"}] my code is working. Firstly the map is loading so it gives an error. Which should I use different method? I hope I could have explained enough.
This is my json data result:
[{"id":48,"title":"a","lng":"28.6643180847168","lat":"41.0327529907227"}, {"id":46,"title":"b","lng":"28.6722145080566","lat":"41.0330085754395 "}, {"id":44,"title":"c","lng":"28.6628570556641","lat":"41.032169342041 "}, {"id":43,"title":"d","lng":"28.6649876832962","lat":"41.0323740058176 "}];
This is index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<style>
html, body, #map-canvas {height: 100%;margin: 0;padding: 0;}
</style>
</head>
<body>
<div id="one"></div>
<div id="map-canvas"></div>
<script>
$(window).load(function () {
$.ajax({
dataType: "json",
url: 'ajax.php',
success:function(data){
var result = JSON.stringify(data);
$("#one").html(result);
}
});
});
var map;
var json=$("#one").text();
function initialize() {
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(json[0]['lat'],json[0]['lng'])
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Looping through all the entries from the JSON data
for(var i = 0; i < json.length; i++) {
var obj = json[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(obj.lat,obj.lng),
map: map
});
var clicker = addClicker(marker, obj.title);
}
function addClicker(marker, content) {
google.maps.event.addListener(marker, 'click', function() {
if (infowindow) {infowindow.close();}
infowindow = new google.maps.InfoWindow({content: content});
infowindow.open(map, marker);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>
Aucun commentaire:
Enregistrer un commentaire