I have a JavaScript ajax page, which fires an ajax request (using setInterval function) every 20 seconds and gets response in JSON format. In the page; using JSON response I'm displaying the markers on Google map (using API v3) and updating them every 20 seconds based on the location received from ajax response. I'm displaying an infoWindow on click event of marker.
I am using PHP as server side scripting, which generates my ajax response by doing some DB calls.
Everything works fine when I open the page. But slowly the page starts responding slow. I mean when I click on the marker or on related text, page takes a significant time to locate the marker, to load the map and to open the infoWindow. And the slowness of page increases as the time passes. If I refresh the page, again everything starts working fine.
The page don't even show a single error at any point of time and I must add that the auto updation of location of markers works fine throughout the life of the page.
I've tried everything which I found on forums. Like, I've moved to json response from an xml(dom) response. I've tried changing the XMLHttpRequest methods, as the GET requests have tendency to auto cache the data. But nothing helped me. I am completely clueless, what is wrong, what I am doing in my code.
Here is my JavaScript code:
<script type="text/javascript">
var map;
var contentString = "";
var infoWindow = new google.maps.InfoWindow({content: contentString});
var url = "genAjaxResponse.php?id=<?php echo $id; ?>";
var marker;
var gmarkers = new Array();
var icon;
var lastClickedMarker;
var stImgId;
var customIcons = {
Moving: {
icon: 'icons/abc.png'
},
Idle: {
icon: 'icons/xyz.png'
},
Parked: {
icon: 'icons/pqr.png'
},
Alert: {
icon: 'icons/wxy.png'
}
};
function load() { // to be called on onload event of body
map = new google.maps.Map(document.getElementById("map"), {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true,
center:new google.maps.LatLng(15.570128,78.957092)
});
calldownloadUrl(url,map,infoWindow);
directionsDisplay = new google.maps.DirectionsRenderer();
}
function calldownloadUrl(url,map,infoWindow) {
downloadUrl(url,displayMarker,map,infoWindow);
}
function displayMarker(data,map,infoWindow) {
function generateTriggerCallback(object, eventType) {
return function() {
google.maps.event.trigger(object, eventType);
};
}
var namearr = Array();
var json = data.responseText;
var vehicles = eval ("(" + json + ")");
var i = 0;
for (var veh in vehicles)
{
var tag = vehicles[veh];
var veh_no = tag["veh_no"];
var is_stale = tag["is_stale"];
var ignition_off = tag["ignition_off"];
var speed = tag["speed"];
var lat = tag["lat"];
var lng = tag["lng"];
var time = tag["time_stamp"];
var address = tag["address"];
var point = new google.maps.LatLng(
parseFloat(lat),
parseFloat(lng));
var type;
var status;
stImgId = i+1;
if(ignition_off == 0 && speed > 3) {
type = "Moving";
status = type + "(" + speed + " Kmph)";
document.getElementById("img"+stImgId).src = "icons/greenalert2.png";
}
else {
if(ignition_off == 1) {
type = "Parked";
status = type;
document.getElementById("img"+stImgId).src = "icons/greyalert2.png";
}
else {
type = "Idle";
status = type;
document.getElementById("img"+stImgId).src = "icons/yellowalert2.png";
}
}
if(is_stale == 1) {
type = "Alert";
status = type;
document.getElementById("img"+stImgId).src = "icons/redalert2.png";
}
infoWindow.close();
var icon = customIcons[type] || {};
if(typeof gmarkers[i] != 'undefined') {
gmarkers[i].setPosition(point);
gmarkers[i].setIcon(icon.icon);
if(gmarkers[i].id == lastClickedMarker) {
if(map.getBounds().contains(gmarkers[i].getPosition()) === false)
map.setCenter(gmarkers[i].getPosition());
}
}
else
{
gmarkers[i] = new google.maps.Marker({
id: i,
position: point,
icon: icon.icon,
title: veh_no,
map: map
});
}
var html = "<span><p><b>"+veh_no +"</b></p> <p>Address: "+address+"<br />Status: "+status+"<br />Time: "+time+"</p></span>";
namearr[i] = "<span><p><b>"+veh_no +"</b></p> <p>Address: "+address+"<br />Status: "+status+"<br />Time: "+time+"</p></span>";
// -- bind click event to texts (vehicle nos) -- //
var textclick = document.getElementById(i);
textclick.onclick = generateTriggerCallback(gmarkers[i],"click");
// -- bind click event to markers -- //
bindinfoWindow(gmarkers[i], map, infoWindow, namearr[i], icon);
i++;
}
}
function bindinfoWindow(marker, map, infoWindow, html, icon) {
google.maps.event.addListener(marker, 'click', function() {
lastClickedMarker = marker.id;
map.setCenter(marker.getPosition());
if(map.zoom < 15)
map.setZoom(15);
marker.setIcon(icon.icon);
marker.setZIndex(google.maps.Marker.MAX_ZINDEX + 1);
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback, map, infoWindow) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, map, infoWindow, request.status);
}
};
request.open('GET', url, true);
request.send();
}
function doNothing() {}
window.setInterval(function() {calldownloadUrl(url,map,infoWindow)},20000);
</script>
I've a similar app and I've also ran into similar behavior.
In my case, I've been updating an array of markers every 30 secs (for each marker: location, icon, content of a listener).
Firstly, I have stopped creating a new marker each update, I thought that setting markers[id].setMap(null); and creating new one will be OK, that CG will handle this.
Then I've changed the code to only update markers position, icon and listener, like this:
this.markers[id].setPosition(new google.maps.LatLng(lat, lng));
this.markers[id].setIcon(this.updateFlags(status, id));
google.maps.event.addListener(this.markers[id], 'mouseover', function () {
infoWindow.setContent(text);
infoWindow.open(this.map, this);
});
google.maps.event.addListener(this.markers[id], 'click', function () {
devices.selectDevice(index);
});
This produced much less consumed memory, but still...
Finally I've edited code like this:
this.markers[id].setPosition(new google.maps.LatLng(lat, lng));
this.markers[id].setIcon(this.updateFlags(status, id));
google.maps.event.clearListeners(this.markers[id], 'mouseover');
google.maps.event.clearListeners(this.markers[id], 'click');
google.maps.event.addListener(this.markers[id], 'mouseover', function () {
infoWindow.setContent(text);
infoWindow.open(this.map, this);
});
google.maps.event.addListener(this.markers[id], 'click', function () {
devices.selectDevice(index);
});
I've tested it in Chrome Developer Tools (F12) -> Profiler and Take Heap Snapshot. And you will see if it grows too fast.
So in your case it would mean adding this line as the first line of function bindinfoWindow():
google.maps.event.clearListeners(marker, 'click');
I think you need to empty the gmarkers array each time you calling that ajax request, or reset the i variable before you processing the received data. In this way you are not adding all the new markers to the previous ones, which seems is the bottleneck in your code.
P.S. I didn't test your code. I'm just guessing.
Related
I am using gmap3 plugin to show google map. In my case I have stored all the information of properties in the database(mysql) with custom markers. Now I want that when the page is loaded it will display all the markers in google map.
For loading googlemap with gmap3 plugin I am using this code
function loadMap() {
jQuery(document).ready(function(){
if(typeof gMap == 'undefined') {
//// CREATES A MAP
gMap = jQuery('#map-canvas');
gMap.gmap3({
map: {
options: {
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
scrollwheel: true,
streetViewControl: false
}
}
});
}
});
}
and inside div ``map-canvas I can see the map. But can some one kindly tell me how to show all the markers with the positions? Any help and suggestions will be really appreciable. Thanks.
Update
If I am wrong with my codes then someone can show their codes to me. I am using Gmap3 plugin.
I am not sure about this it will work in gmap3 but i use this code for creating my costome icon hope it will help you
In the index.php use this for creating your costom icon pathlike this
<?php
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
$a=array();
while ($row = #mysql_fetch_assoc($result)){ $a='$row[\'type\']'=>array('icon'=>'$row[\'path\']','shadow'=>'$row[\'path2\']')
}
$a=json_encode($a);
?>
it should be done before js file after that
write this
<script>
var customIcons= <?php echo $a; ?>;
</script>
and finally load your map and infoWindowbox() in that function
function infoWindowbox() {
downloadUrl("xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
animation: google.maps.Animation.DROP
});
markerArray.push(marker);
bounds.extend(marker.position);
bindInfoWindow(marker, map, infoWindow, html);
}
map.fitBounds(bounds);
// var markerCluster = new MarkerClusterer(map, markerArray);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
gmap3 initializator has a marker attribute that allows you to create markers.
See example with single and multiple markers here:
http://gmap3.net/en/catalog/10-overlays/marker-41
I think this example might help.
Updated:
If you want to read the data like from database (or) xml, You can then make an ajax request to that page (from any page on your site) using jQuery:
I have an example but this is with xml to get the data from xml file.
$.ajax({
url: 'categories.xml (or) your database path',
type: 'get',
success: function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new GLatLng(lat,lng);
var address = markers[i].getAttribute("address");
var name = markers[i].getAttribute("name");
var html = "<b>"+name+"<\/b><p>"+address;
var category = markers[i].getAttribute("category");
// create the marker
var marker = createMarker(point,name,html,category);
map.addOverlay(marker);
}
// == show or hide the categories initially ==
show("theatre");
hide("golf");
hide("info");
// == create the initial sidebar ==
makeSidebar();
});
});
Like this you may get the data from database also through using queries. Try this one atleast you may get the idea.
The gmaps3 plugin documentation shows how to add markers. If you create an options array in php through ajax/json and feed that to the markers: option your markers should be added.
In my PHP file, I create an array of arrays, and use json_encode to make this array usable in javascript. When I echo this direction within the tags it works perfectly. However, I need the PHP to be run at regular intervals (I'm using setTimeout), so I'm trying to use AJAX to call the php and get that array to be used in the javascript function.
Here is the PHP:
$bubbles = array();
$result = mysql_query("SELECT text, lat, lng FROM bubbles");
while($row = mysql_fetch_array($result)){
$newbubble = array($row[0],$row[1],$row[2],'female-2.png');
$bubbles[] = $newbubble;
}
$js_array = json_encode($bubbles);
echo"$js_array";
And here is the javascript/AJAX portion in question:
setTimeout(initializeMaps, 5000);
function initializeMaps() {
var markers;
var ajax;
ajax=new XMLHttpRequest();
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
var markers = ajax.responseText;
}
}
ajax.open("GET","ajax-getbubbles.php",true);
ajax.send();
/*The markers variable needs to be used in the following code*/
var iconBase = 'http://picaflora.com/uniproject/images/';
var infowindow = new google.maps.InfoWindow(), marker, i;
for (i = 0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i][1], markers[i][2]),
map: map,
icon: iconBase + markers[i][3]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(markers[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
setTimeout(initializeMaps, 5000);
}
If I alert() or console.log(), all the data is coming back from PHP just fine. But somehow it seems that the rest of the script just isn't doing anything with the variable markers. I'm not too familiar with javascript, just familiar enough to tinker and try things till it works, so if you think there might be a better way to approach the problem, then by all means go for it. I'd rather not look into jQuery solutions at this point, unless it's necessary. Thanks!
You have to decode the encoded JSON string at the javascript's end before you can use it as a variable.
Instead of
var markers = ajax.responseText;
use
var markers = JSON.parse(markers);
Try this-
setTimeout(initializeMaps, 5000);
function initializeMaps() {
var markers;
var ajax;
ajax=new XMLHttpRequest();
ajax.onreadystatechange=function(){
if (ajax.readyState==4 && ajax.status==200){
var markers = JSON.parse(ajax.responseText);
update(markers);
}
}
ajax.open("GET","ajax-getbubbles.php",true);
ajax.send();
}
function update(markers){
var iconBase = 'http://picaflora.com/uniproject/images/';
var infowindow = new google.maps.InfoWindow(), marker, i;
for (i = 0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i][1], markers[i][2]),
map: map,
icon: iconBase + markers[i][3]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(markers[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
PS- I'm not sure why are calling setTimeout(initializeMaps, 5000); twice.
Javascript is asynchronous unlike PHP. All of that javascript code where you do things with the markers is being executed immediately before you have received a response. What you need to do is wrap it in a function:
function myFunc(markers) {
// all of your code to do stuff
}
Then call that function when the response state changes:
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
var markers = ajax.responseText;
myFunc(markers);
}
}
I want to display multiple directions with dragable waypoints and save each waypoints.
On my project I can click on the map to create the routes, generating a wayA point and a wayB point and draw a route between them. So, I can make multiple routes.
I can also save them on the database.
The problem is load this points on the map again fetching them on the database and drawing all on the map.
I have two pages, on index.htm you can draw your routes and save them, and on loady.htm you can load them on the map.
I tried somethings but without sucess, I will post my try here.
This is my resumed index.htm
var map, ren, ser;
var data = {};
var wayA = [];
var wayB = [];
var directionResult = [];
function goma() <---Initialize
{
google.maps.event.addListener(map, "click", function(event) {
if (wayA.length == wayB.length) {
wayA.push(new google.maps.Marker({
draggable: true,
position: event.latLng,
map: map
}));
} else {
wayB.push(new google.maps.Marker({
draggable: true,
position: event.latLng,
map: map
}));
ren = new google.maps.DirectionsRenderer( {'draggable':true} );
ren.setMap(map);
ren.setPanel(document.getElementById("directionsPanel"));
ser = new google.maps.DirectionsService();
ser.route({ 'origin': wayA[wayA.length-1].getPosition(), 'destination': wayB[wayB.length-1].getPosition(), 'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK') {
directionResult.push(res);
ren.setDirections(res);
} else {
directionResult.push(null);
} })
} }); }
function save_waypoints()
{
var w=[],wp;
var rleg = ren.directions.routes[0].legs[0];
data.start = {'lat': rleg.start_location.lat(), 'lng':rleg.start_location.lng()}
data.end = {'lat': rleg.end_location.lat(), 'lng':rleg.end_location.lng()}
var wp = rleg.via_waypoints
for(var i=0;i<wp.length;i++)w[i] = [wp[i].lat(),wp[i].lng()]
data.waypoints = w;
var str = JSON.stringify(data)
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=save&inventoresdegara='+str)
jax.onreadystatechange = function(){ if(jax.readyState==4) {
if(jax.responseText.indexOf('bien')+1)alert('Mapa Atualizado !');
else alert(jax.responseText)
}}
}
This is the resumed loady.htm with my try
var map, ren, ser;
var data = {};
var wayA = [];
var wayB = [];
var directionResult = [];
function goma() {
ren = new google.maps.DirectionsRenderer( {'draggable':true} );
ren.setMap(map);
ren.setPanel(document.getElementById("directionsPanel"));
ser = new google.maps.DirectionsService();
fetchdata();
function setroute(os)
{
var wp = [];
for(var i=0;i<os.waypoints.length;i++)
wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][3]),'stopover':false }
ser.route({ 'origin': wayA[wayA.length-1].setPosition(), 'destination': wayB[wayB.length-1].setPosition(), 'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK') {
directionResult.push(res);
ren.setDirections(res);
} else {
directionResult.push(null);
}
});
}
function fetchdata()
{
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=fetch')
jax.onreadystatechange = function(){ if(jax.readyState==4) {
try { setroute( eval('(' + jax.responseText + ')') ); }
catch(e){ alert(e); }
}}
}
This is my php file:
<?
if($_REQUEST['command']=='save')
{
$query = "insert into inventoresdegara set value='$data'";
if(mysql_query($query))die('bien');
die(mysql_error());
}
if($_REQUEST['command']=='fetch')
{
//$query = "select value from inventoresdegara";
$query = "SELECT value FROM inventoresdegara";
if(!($res = mysql_query($query)));
$rs = mysql_fetch_array($res,1);
die($rs['value']);
}
?>
This is a image from my database to you know how the information are saved
The only thing that I need to do is load this values to the map, please help me =).
Thanks !
After my try, the loady.htm was this on ser.routes
ser.route({'origin':new google.maps.LatLng(os.start.lat,os.start.lng),
'destination':new google.maps.LatLng(os.end.lat,os.end.lng),
'waypoints': wp,
'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK')ren.setDirections(res);
}
If the reason to saving waypoints is to reproduce the route they came from, you're better off saving the entire route and then showing it on the map without re-requesting the route again. See Displaying results of google direction web service without using javascript api
Otherwise, if you just want to get a fresh route from A to B through waypoints, your current approach of calling ser.route() with them is correct.
I'm connecting a Google Map to a MySQL database to list distributors all over the world, and I seem to be having a few issues.
Sometimes the page itself will not load at all in Firefox (v4 on Mac). It's temperamental on my machine (FF v3.6 Mac) and a Windows machine (FF v4 Win 7), ok in Safari/Opera, doesn't load at all in IE 9 (Win 7). Not sure if it's a network issue or code.
Load time is pretty slow. Might be because the map covers the whole page (will create a square block to place it in).
The URL of the page is here and I used the code from Sean Feeney's page.
The code I have is:
<script src="http://maps.google.com/maps?file=api&v=2&key=<I entered my key here>" type="text/javascript"></script>
<body onUnload="GUnload()">
<div id="map" style="position:absolute;top:0px;bottom:0px;left:0;right:0;"></div>
</body>
<script type="text/javascript">
//<![CDATA[
var map;
var latlngbounds;
if (GBrowserIsCompatible()) {
function createMarker(point, address) {
var marker = new GMarker(point);
var html = address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
function extendBounding(point) {
latlngbounds.extend(point);
var zoom = map.getBoundsZoomLevel(latlngbounds);
if (zoom < 10) {
zoom = 12;
}
map.setCenter(latlngbounds.getCenter(), zoom);
}
}
map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
latlngbounds = new GLatLngBounds();
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var address = markers[i].getAttribute("address");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, address);
map.addOverlay(marker);
extendBounding(point);
}
});
}
//]]>
</script>
The code that gets the data is the same as the example.
Any ideas as to why it doesn't always load in the browsers, and why it seems to take a while to load?
Thanks,
Adrian
Ideally you should wrap the code that loads the map inside a document ready or window load event.
I notice that your code is not nested properly inside the GBrowserIsCompatible() block so please fix that.
As far as I remember, Google maps API v2 requires you to call the setCenter() method before doing any operations on the map. So to begin with, set the center to (0, 0) immediately after creating the map.
I notice that you're downloading XML data before you add markers to the map. You must take into account the time taken by the server to serve the XML data. If you've called the setCenter() before downloading the XML, the map will display while the XML downloads asynchronously.
Inside the code that handles the XML data: when you add a marker, do not call setCenter() immediately. Doing so will cause the function to be called 1000 times if you have 1000 markers in your XML. Instead, just call latlngbounds.extend(point). Once you have iterated the loop, calculate the zoom/center and call setCenter(). This way you will end up calling this function only twice.
Edit
I've figured out what the problem is. The genxml.php randomly returns the string Google Geo error 620 occurred which cannot be parsed as XML which raises JavaScript errors and no markers are shown. Better have a look at the code of that file and see why this happens randomly. On other times when that file actually returns valid XML, the markers appear as expected.
It appears Google recently tightened geocoding requests. If you send 10 too fast, it cuts you off with 620 error. The solution they recommend is adding a dynamic timer. Other stackoverflow posts suggested a 0.25 second static timer was good enough, but I've found Google's recommendation of using a while loop that increments the timer value as needed works better. For example:
// Initialize delay in geocode speed
public $delay = 0;
public function lookup(arguments)
{
$geocode_pending = true;
while ($geocode_pending) {
$search = //address string to search;
$response = $this->performRequest($search, 'xml');
$xml = new SimpleXMLElement($response);
$status = (int) $xml->Response->Status->code;
switch ($status) {
case self::G_GEO_SUCCESS:
require_once('placemark.php');
$placemarks = array();
foreach ($xml->Response->Placemark as $placemark)
$placemarks[] = Placemark::FromSimpleXml($placemark);
$geocode_pending = false;
return $placemarks;
case self::G_GEO_TOO_MANY_QUERIES:
$delay += 100000;
case self::G_GEO_UNKNOWN_ADDRESS:
case self::G_GEO_UNAVAILABLE_ADDRESS:
return array();
default:
throw new Exception(sprintf('Google Geo error %d occurred', $status));
}
usleep($delay);
}
}
You can run your map code with window.load after everything is loaded:
jQuery(document).ready(function initAutocomplete() {
var p_lag=$('#longitude').val();
var p_lat=$('#latitude').val();
if(p_lat==''){
var p_lat=20.593684;
}
if(p_lag==''){
var p_lag=78.96288000000004 ;
}
var myLatLng = {lat: p_lat,lng: p_lag};
var map = new google.maps.Map(document.getElementById('dvMap'), {
center: myLatLng,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: myLatLng,
draggable: true,
map: map,
title: 'Map'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
//map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
//Click event for getting lat lng
google.maps.event.addListener(map, 'click', function (e) {
$('input#latitude').val(e.latLng.lat());
$('input#longitude').val(e.latLng.lng());
});
google.maps.event.addListener(marker, 'dragend', function (e) {
$('input#latitude').val(e.latLng.lat());
$('input#longitude').val(e.latLng.lng());
});
var markers = [];
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
/*markers.forEach(function (marker) {
marker.setMap(null);
});*/
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
$('#latitude').val(place.geometry.location.lat());
$('#longitude').val(place.geometry.location.lng());
marker.setPosition(place.geometry.location);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
});
}
);
I have a big dilema. I want to load a .html file which contains javascript(google maps) code to render the div inside it.
maps.html look like this :
<script type="text/javascript">
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
</script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var hash = getUrlVars();
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(hash['lat'],hash['lng']),
zoom: 14,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("xmlout_carol.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length+1; i++) {
var name = markers[i].getAttribute("nume");
var address = markers[i].getAttribute("adresa");
var type = markers[i].getAttribute("id");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<font face='Tahoma' style='font-size:12px;'><div style='min-width:230px;'><b>" + name + "</b> <br/>" + address +"<a target='_top' href='../statii.php?id=" + type + "'><img style='float:right; border:0px; margin-left: 40px;' src='go.png' /></a><div/></font>";
var tip = markers[i].getAttribute("tip");
var icon = customIcons[tip] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
// shadow: 'shaddow.png'
//shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'mouseover', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
google.maps.event.addListener(map, 'click', function() {
infoWindow.close(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
<body onload="load()">
<div id="map" style="width: 900px; height: 500px"></div>
</body>
this script render the map to the div.map
What i want to do is to load this .html into a div that is contained in another .php file like this :
$("div#insert_here").load("maps.html?lat=xxx&long=yyy");
It output the div contained in maps.html but with no map no java.
So the question is... How do I load a .html file using jquery in another .php file if the .html file already contains javascripts to output data to the div in .html file ???
Thanks a lot !
Instead of loading a file which has both HTML and JavaScript in it, can you load the JavaScript with the page initially, make an ajax call for the HTML, and call the JavaScript once the ajax request is complete? This will solve a lot of headaches with this issue.
As the others said, load JS particularly, or do the eval() function ;).
That parses the JS and makes it possible to be executed initially.
I dont use load and get much it almost always seems better to use $.ajax or $.post (more flexibility, I also suggest calling json and using the dataType:"json". Again more flexible).
Use callbacks after success to run the javascript you need once the ajaxed html is loaded into the page. You call use beforeSend to load script you need (although unless there is a good reason just add those scripts to the page along with everything else (more robust/cacheable)).
If google_statii.js needs dynamic variables one way would be use hidden inputs on the page with values populated server side and then call them within the script.
ie. var x = $("input#myHiddenVariable");