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:
$.ajax({
url: '<?=base_url()?>index.php/guide/getMap',
success: function(data) {
function initialize() {
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var mapCanvas = document.getElementById("map_canvas");
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP}
map = new google.maps.Map(mapCanvas, myOptions);
}
}
});
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.
Try this.I Think this will work.Place the below code on bottom of your page:
$.ajax({
url: '<?=base_url()?>index.php/guide/getMap',
success: function(data) {
$('.result').text(data);
initialize();
}
});
Related
I have a working Google Map on my site using Google Maps API v3.
The map is loaded on pageload and applied with multiple markers/positions from an array of coordinates.
Now, what I want to do is to dynamically update the markers/positions with a new array of coordinates with an ajax call.
Here is an example of my markup:
<div id="map-canvas"></div>
<script type="text/javascript">
var LocationData = <?php echo $coordsarray; ?>;
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
draggable: true
} );
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (var i in LocationData)
{
var p = LocationData[i];
var latlng = new google.maps.LatLng(p[0], p[1]);
bounds.extend(latlng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: p[2]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.title);
infowindow.open(map, this);
});
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
//Ajax call
var interval = 5000; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
jQuery.ajax({
type: 'POST',
url: '/codes/LiveVisitsStats/postlivecounter.php',
dataType : 'html',
success: function (data) {
var arr = data.split('|');
jQuery('#counterint').html(arr[0]);
jQuery('#extrainfoscounter').html(arr[1]);
},
complete: function (data) {
// Schedule the next
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);
</script>
So what I now need to do is to send an array of coordinated via the Ajax call and on success update the existing Google Map with new coordinates.
I have tried to find a documentation of this but no luck..
If someone knows a good way to do this please help.
I ended up choosing a completely different approach. Here is the code I used, which works
<script type="text/javascript">
var locations = {}; //A repository for markers (and the data from which they were contructed).
//initial dataset for markers
var locs = {
1: {
info: '11111. Some random info here',
lat: -37.8139,
lng: 144.9634
},
2: {
info: '22222. Some random info here',
lat: 46.0553,
lng: 14.5144
},
3: {
info: '33333. Some random info here',
lat: -33.7333,
lng: 151.0833
},
4: {
info: '44444. Some random info here',
lat: 27.9798,
lng: -81.731
}
};
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 1,
maxZoom: 8,
minZoom: 1,
streetViewControl: false,
center: new google.maps.LatLng(30, 30),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
function setMarkers(locObj) {
jQuery.each(locObj, function (key, loc) {
if (!locations[key] && loc.lat !== undefined && loc.lng !== undefined) {
//Marker has not yet been made (and there's enough data to create one).
//Create marker
loc.marker = new google.maps.Marker({
position: new google.maps.LatLng(loc.lat, loc.lng),
map: map
});
//Attach click listener to marker
google.maps.event.addListener(loc.marker, 'click', (function (key) {
return function () {
infowindow.setContent(locations[key].info);
infowindow.open(map, locations[key].marker);
}
})(key));
//Remember loc in the `locations` so its info can be displayed and so its marker can be deleted.
locations[key] = loc;
} else if (locations[key] && loc.remove) {
//Remove marker from map
if (locations[key].marker) {
locations[key].marker.setMap(null);
}
//Remove element from `locations`
delete locations[key];
} else if (locations[key]) {
//Update the previous data object with the latest data.
jQuery.extend(locations[key], loc);
if (loc.lat !== undefined && loc.lng !== undefined) {
//Update marker position (maybe not necessary but doesn't hurt).
locations[key].marker.setPosition(
new google.maps.LatLng(loc.lat, loc.lng));
}
//locations[key].info looks after itself.
}
});
}
setMarkers(locs); //Create markers from the initial dataset served with the document.
//ajaxObj.get(); //Start the get cycle.
// *******************
//Ajax code
var interval = 5000; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
jQuery.ajax({
type: 'POST',
url: '/codes/LiveVisitsStats/postlivecounter.php',
dataType : 'html',
success: function (data) {
var arr = data.split('|');
jQuery('#counterint').html(arr[0]);
jQuery('#extrainfoscounter').html(arr[1]);
jQuery('#testdiv').html(arr[2]);
//test: simulated ajax
var testLocs = {
1: {
info: '1. New Random info and new position',
lat: -37,
lng: 124.9634
},
2: {
lat: 70,
lng: 14.5144
},
3: {
info: '3. New Random info'
},
4: {
remove: true
},
5: {
info: '55555. Added',
lat: -37,
lng: 0
}
};
setMarkers(testLocs);
},
complete: function (data) {
// Schedule the next
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);
</script>
I use this script to get the markers for Google Maps with JSON.
It is not working because I need to receive the boundary in the Json script like this:
$swLat=$_GET["swLat"];
$swLon=$_GET["swLon"];
$neLat=$_GET["neLat"];
$neLon=$_GET["neLon"];
That is where I need your help.
Google maps script
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript" src="http://skiweather.eu/gmap3/js/jquery.ui.map.js"></script>
<script language="javascript" type="text/javascript">
var map = null;
map = new google.maps.Map(document.getElementById("map"));
var markers = new Array();
var bounds = map.getBounds();
var zoomLevel = map.getZoom();
$(function() {
demo.add(function() {
$('#map').gmap().bind('init', function() {
$.getJSON( 'http://skiweather.eu/gmap3/markers/index.php', {zoom: zoomLevel,
swLat: bounds.getSouthWest().lat(), swLon: bounds.getSouthWest().lng(),
neLat: bounds.getNorthEast().lat(), neLon: bounds.getNorthEast().lng()}, function(data) {
$.each( data.markers, function(i, marker) {
$('#map').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'bounds': true
}).click(function() {
$('#map').gmap('openInfoWindow', { 'content': marker.content }, this);
});
});
});
});
}).load();
});
</script>
</head>
<body>
<div id="map"></div>
The jQuery/gmap-part of your code will not be executed at all.
Fixed code:
<script type="text/javascript">
$(function() {
$('#map').gmap().bind('init', function() {
var markers = new Array();
var bounds = $(this).gmap('get','map').getBounds();
var zoomLevel = $(this).gmap('get','map').getZoom();
$.getJSON( 'http://skiweather.eu/gmap3/markers/index.php', {zoom: zoomLevel,
swLat: bounds.getSouthWest().lat(), swLon: bounds.getSouthWest().lng(),
neLat: bounds.getNorthEast().lat(), neLon: bounds.getNorthEast().lng()}, function(data) {
$.each( data.markers, function(i, marker) {
$('#map').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'bounds': true
}).click(function() {
$('#map').gmap('openInfoWindow', { 'content': marker.content }, this);
});
});
});
});
});
</script>
However, it's sending the data now, but it's still not working, because the server will not give any response(are you sure that there is a webservice that returns JSON-data?)
How to remove the old marker with time interval and replace it with new marker automatically. I'm creating a real tracker using google map. `
var markersArray = [];
function initialize() {
var myLatlng = new google.maps.LatLng(39, -86);
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 1,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
$(function () {
$(document).ready(function(){
setInterval(function(){
$.ajax({
url: 'real.php', //the script to call to get data
//data: "",
dataType: 'json', //data format
success: function(data){ //on recieve of reply
var locations = data;
var infowindow = new google.maps.InfoWindow();
var marker, i;
deleteOverlays();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
markersArray.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
});
}, 1000);
});
});
}
initialize();
How can I delete the markers I've used the clearOverlays but no markers are shown in the map. Thanks.
To remove a marker, you need to set its map to null:
for (var ii = 0; ii < markers.length; ii++) {
markers[ii].setMap(null);
}
Or, depending on your scenario, you could just update the marker's location:
marker.setPosition(newLatLng);
I'm trying to do two things from the code below:
If the geocode is not successfull don't show the map (so far I've only hidden the error message.)
If it is successful only load the address and not the original latlng before reloading the address.
You'll have to excuse all the single quote marks, the javascript loads under a php echo.
Any ideas welcome, ideally I'd like to handle it in the javascript but don't mind a bit of php if needed, I'm looking to use this in a few areas of the site.
echo '
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(51.500141,-0.125195);
var address = \''.$company.', '.$address_l1.', '.$address_l2.', '.$address_l3.', '.$town.', '.$county.', '.$post_code.', '.$country.'\';
var myOptions = {
zoom: 16,
scrollwheel: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder.geocode( { \'address\': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
<div id="map_canvas"></div>
';
Move the map creation into the success function of geocode and use document.getElementById('map_canvas').style.display='block' or none to show/hide the map on fail.
I'm having an issue with setting up the info windows for multiple markers in google map api. Basically, Im getting the latitudes and longitudes and everything else from external Json file. I'm parsing it correctly because markers are showing on the map. However, when I'm trying to add an info window for each one of them it only show info window for the most recent added marker + whenever I point on different marker it will still go to this latest marker showing its info window. Here's the source code:
function initialize()
{
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("tab14"), myOptions);
/* Sets up markers */
markers = [];
for (var i = 0, coordinates; coordinates = data.coords[i]; i++)
{
//marker = new google.maps.LatLng(coordinates.latitude, coordinates.longitude);
var iconImage = new google.maps.MarkerImage("http://map.lgfl.org.uk/images/arrow_green.png");
var LatLng = new google.maps.LatLng(coordinates.latitude, coordinates.longitude);
var marker = new google.maps.Marker({position: LatLng, icon: iconImage });
var contentString = '<div>'+
'<div>'+
'</div>'+
'<h4>'+coordinates.title+'</h1>'+
'<div>'+
'<p>'+coordinates.excerpt+'</p>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
markers.push(marker);
}
/* Sets up marker clusterer */
var markerCluster = new MarkerClusterer(map, markers);
}
Can someone please give me some help with this? Thanks.
//Edited------------------------------------------------------
So I've changed it and now it looks like this:
infoWindow = new google.maps.InfoWindow();
for (var i = 0, coordinates; coordinates = data.coords[i]; i++)
{
//marker = new google.maps.LatLng(coordinates.latitude, coordinates.longitude);
var iconImage = new google.maps.MarkerImage("http://map.lgfl.org.uk/images/arrow_green.png");
var LatLng = new google.maps.LatLng(coordinates.latitude, coordinates.longitude);
var marker = new google.maps.Marker({position: LatLng, icon: iconImage });
var contentString = '<div>'+
'<div>'+
'</div>'+
'<h4>'+coordinates.title+'</h1>'+
'<div>'+
'<p>'+coordinates.excerpt+'</p>'+
'</div>'+
'</div>';
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(contentString);
infoWindow.open(map,marker);
});
markers.push(marker);
}
/* Sets up marker clusterer */
var markerCluster = new MarkerClusterer(map, markers);
Still doesn't work :/
As far as I know, you can only have one InfoWindow. You should add a onclick event to each marker in which you define the content of the window.
I think you should change:
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
to something like:
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
The infoWindow should be defined outside your for loop.
Good luck!
** EDIT **
I think you need to use unique names for your markers.
This is a working example:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false&key=
<<INSERT YOUR KEY HERE>>" type="text/javascript"></script>
<script>
function initialize() {
// Create google map
var latlng = new google.maps.LatLng(31.0293534,5.1736923);
var myOptions = {
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 1,
backgroundColor: "#99B3CC",
mapTypeControl: false
}
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var infoWindow = new google.maps.InfoWindow();
/**
* First marker
*/
var latLng = new google.maps.LatLng(31.0293534,5.1736923);
var marker1 = new google.maps.Marker({
map: map,
position: latLng,
visible: true
});
google.maps.event.addListener(marker1, 'click', function() {
infoWindow.setContent("Some content Marker 1");
infoWindow.open(map,marker1);
});
/**
* Second marker
*/
var latLng = new google.maps.LatLng(25.271139,55.307485);
var marker2 = new google.maps.Marker({
map: map,
position: latLng,
visible: true
});
marker2.onclick = function() {
infoWindow.setContent("Some content marker2");
infoWindow.open(map,marker2);
};
google.maps.event.addListener(marker2, 'click', function() {
infoWindow.setContent("Some content marker2");
infoWindow.open(map,marker2);
});
}
window.onload=initialize;
</script>
</head>
<body>
<div id="map" style="width: 400px; height: 400px;"></div>
</body>
</html>
You may have to change the key. But at my place this works like a charm. The most simple example I can give you.
Ok I've found a solution to this. It's kinda a hack but it works for me. I'm putting it here in case someone else would need it:
<script type="text/javascript">
/* Sets up the map with markers */
function initialize()
{
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("tab14"), myOptions);
/* Sets up markers */
markers = [];
infoWindow = new google.maps.InfoWindow();
for (var i = 0, coordinates; coordinates = data.coords[i]; i++)
{
var iconImage = new google.maps.MarkerImage("http://map.lgfl.org.uk/images/arrow_green.png");
var LatLng = new google.maps.LatLng(coordinates.latitude, coordinates.longitude);
var marker = new google.maps.Marker({position: LatLng, icon: iconImage });
var contentString = '<div>'+
'<h4>'+coordinates.title+'</h1>'+
'<div>'+
'<p>'+coordinates.excerpt+'</p>'+
'</div>'+
'</div>';
addMarker(marker, contentString);
markers.push(marker);
}
/* Sets up marker clusterer */
var markerCluster = new MarkerClusterer(map, markers);
function addMarker(marker, content)
{
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(content);
infoWindow.open(map, marker);
});
}
}
</script>