I’ve got the following code to get some Javascript back from the server:
$.ajax({
url: '<?=base_url()?>index.php/guide/getMap',
success: function(data) {
$('.result').text(data);
alert('Load was performed.');
}
});
This successfully returns the code I want:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var map; // Global declaration of the map
var iw = new google.maps.InfoWindow(); // Global declaration of the infowindow
var lat_longs = new Array();
var markers = new Array();
function initialize() {
var myLatlng = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function createMarker(markerOptions) {
var marker = new google.maps.Marker(markerOptions);
markers.push(marker);
lat_longs.push(marker.getPosition());
return marker;
}
window.onload = initialize;
//]]>
</script>
My question is, in place of the alert I currently have on the succsufull callback, how can I place this javascript in the body (or head) of the HTML document so that the Google map is displayed? (Note: I will also have another ajax call to return the required html).
The reason I’m not just doing it straight with JS calling the GMaps API is that I need to do some processing on the server to get the appropriate markers from the database to put on the map etc. I am using this library on the server side to generate the js/html needed to display the map.
Instead of having your initialize function be in the middle of nowhere, tie it in with your callback function doing something like:
You can of course move things around so they look pretty, or however you like it laid out. The important thing is that you call your initialize function after you get the data back from the map and after your maps API is loaded.