Google maps

  • (2 Pages)
  • +
  • 1
  • 2

18 Replies - 9554 Views - Last Post: 21 January 2012 - 08:16 PM

#1 compactbrain  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 35
  • Joined: 21-January 10

Google maps

Posted 20 January 2012 - 01:12 PM

Hi all,

Cant seem to get this map to work. I want to load lat and long from mySQL database and display on the map.
I'm using GDownloadUrl and genxml.php to generate the xml file. I've been staring at this to long and now I'm just blind to all the mistakes. Can someone give me some pointers?
thanks.
<points>
<point lat="47.608940" lng="-122.340141" />
<point lat="47.613590" lng="-122.344391" />
<point lat="47.624561" lng="-122.356445" />
<point lat="47.606365" lng="-122.337654" />
<point lat="47.612823" lng="-122.345673" />
<point lat="47.605961" lng="-122.340363" />
<point lat="47.613976" lng="-122.345467" />
<point lat="47.617214" lng="-122.326584" />
<point lat="47.610126" lng="-122.342834" />
</points>



<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>test</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

  var poly;
  var map;

  function initialize() 
  {
    var chicago = new google.maps.LatLng(47.608940, -122.340141);
    var myOptions = {zoom: 7,center: chicago,mapTypeId: google.maps.MapTypeId.ROADMAP};

    map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

    var polyOptions = {strokeColor: '#000000',strokeOpacity: 1.0,strokeWeight: 3};
    poly = new google.maps.Polyline(polyOptions);
    poly.setMap(map);
    addLatLng();

  }

  function addLatLng() 
  {

    var path = poly.getPath();

        GDownloadUrl("genxml.php", function(data) 
	{
          var xml = GXml.parse(data);
          var node = xml.documentElement.getElementsByTagName("point");
          for (var i = 0; i < node.length; i++) 
	  {
	    var points = node.item(i);
            var latlng = new GLatLng(parseFloat(node[i].getAttribute("lat")),parseFloat(node[i].getAttribute("lng")));
	    path.push(latLng);
          }
        });
   }

</script>
</head>
<body onload="initialize()">
  <div id="map_canvas"></div>
</body>
</html>


Is This A Good Question/Topic? 1
  • +

Replies To: Google maps

#2 thrca  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 28
  • View blog
  • Posts: 65
  • Joined: 21-January 12

Re: Google maps

Posted 21 January 2012 - 08:14 AM

Just a thought, but does your genxml.php actually respond with xml, or does it respond with text/html that looks like xml?

header('Content-Type: text/xml');
echo "<?xml version=\"1.0\"?>\n";
... make xml stuff here, or use xml dom lib ...


Was This Post Helpful? 0
  • +
  • -

#3 compactbrain  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 35
  • Joined: 21-January 10

Re: Google maps

Posted 21 January 2012 - 08:56 AM

yeah It responds with xml. any other ideas?
Was This Post Helpful? 0
  • +
  • -

#4 thrca  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 28
  • View blog
  • Posts: 65
  • Joined: 21-January 12

Re: Google maps

Posted 21 January 2012 - 09:29 AM

It looks like the v3 of the maps api doesn't support GDownloadUrl. I have done this in the past with v2, and I can write you up a v2 sample if you want to see how to replicate your map in the v2. Otherwise, use ajax to load your dataset.
Was This Post Helpful? 0
  • +
  • -

#5 thrca  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 28
  • View blog
  • Posts: 65
  • Joined: 21-January 12

Re: Google maps

Posted 21 January 2012 - 09:44 AM

A little more detail for you...

You are using the v3 api, which is currently (afaik) a slimmed down version of the api, assuming you are getting your data by your own methods, thus it does not include the gdownloadurl nor the xml parser.

You can either include your own xml parser and downloader, or switch to v2 api and use the built in functions.

Microajax downloader:
<script type="text/javascript" src="http://microajax.googlecode.com/svn/trunk/microajax.js"></script>
<!--
use this in place of GDownloadUrl(url) -> microAjax(url);
-->



FWIW, you would probably be better off passing your data as JSON, since then you dont need to parse it and it is directly useable by javascript.
Was This Post Helpful? 0
  • +
  • -

#6 thrca  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 28
  • View blog
  • Posts: 65
  • Joined: 21-January 12

Re: Google maps

Posted 21 January 2012 - 10:57 AM

This was definitely a problem with the google xml parser, or your xml.. Changing to json worked MUCH better...

genjson.php
<?php
header('Content-Type: application/json');

$points = array("points" => array(
  array (
    "lat" => 47.608940,
    "lng" => -122.340141
  ),
  array (
    "lat" => 47.613590,
    "lng" => -122.344391
  ),
  array (
    "lat" => 47.624561,
    "lng" => -122.356445
  ),
  array (
    "lat" => 47.606365,
    "lng" => -122.337654
  ),
  array (
    "lat" => 47.612823,
    "lng" => -122.345673
  ),
  array (
    "lat" => 47.605961,
    "lng" => -122.340363
  ),
  array (
    "lat" => 47.613976,
    "lng" => -122.345467
  ),
  array (
    "lat" => 47.617214,
    "lng" => -122.326584
  ),
  array (
    "lat" => 47.610126,
    "lng" => -122.342834
  )
) );

echo json_encode($points);
?>



map.php
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>test</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script src="http://microajax.googlecode.com/svn/trunk/microajax.js" type="text/javascript"></script>
<script type="text/javascript">

  var poly;
  var map;

  function initialize()
  {
    var seattle = new google.maps.LatLng(47.608940, -122.340141);
    var options = {zoom:14,center:seattle,mapTypeId:google.maps.MapTypeId.ROADMAP};
    map = new google.maps.Map(document.getElementById("map_canvas"),options);

    var polyOptions = {strokeColor: '#000000',strokeOpacity: 1.0,strokeWeight: 3};
    poly = new google.maps.Polyline(polyOptions);
    poly.setMap(map);
    addLatLng();

  }

  function addLatLng()
  {
    var path = poly.getPath();
        microAjax("genjson.php", function(data)
        {
//console.log('received = '+data);
            var json = JSON.parse(data);
            var points = json.points;
//console.log('num points = '+points.length);
            for (var i = 0; i < points.length; i++)
            {
              var point = points[i];
              var latlng = new google.maps.LatLng(parseFloat(point.lat),parseFloat(point.lng));
//console.log('latlng = '+latlng)
              path.push(latlng);
            }
        });
   }

</script>
</head>
<body onload="initialize()">
  <div id="map_canvas"></div>
</body>
</html>




btw, in my code snip, I set the zoom level to 14, since your data set was very small around downtown seattle.
Was This Post Helpful? 1
  • +
  • -

#7 compactbrain  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 35
  • Joined: 21-January 10

Re: Google maps

Posted 21 January 2012 - 11:56 AM

Thanks for the replies. I look into the json, I have never used it before. what would bee the best way to generate the json from the databse?
Was This Post Helpful? 0
  • +
  • -

#8 compactbrain  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 35
  • Joined: 21-January 10

Re: Google maps

Posted 21 January 2012 - 12:26 PM

this is my first attempt, but how do i set the lat lng tage? also for some reason it woudlnt let me edit my last post
<?php
require("dbinfo.php");
header('Content-Type: application/json');

$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}

$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}

$sth = mysql_query("SELECT * FROM markers");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows[] = $r;
}
echo json_encode($rows);;
?>



This post has been edited by compactbrain: 21 January 2012 - 12:29 PM

Was This Post Helpful? 0
  • +
  • -

#9 compactbrain  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 35
  • Joined: 21-January 10

Re: Google maps

Posted 21 January 2012 - 02:20 PM

have it working now, just needed to do a bit more reading on json.
Thanks for the help :bananaman:
Was This Post Helpful? 0
  • +
  • -

#10 thrca  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 28
  • View blog
  • Posts: 65
  • Joined: 21-January 12

Re: Google maps

Posted 21 January 2012 - 03:52 PM

Glad you got it working.

As a good coding practice, only select the specific columns you need from the sql (lat,lng) to put into the array which you will encode. This will keep the size of your dataset at its smallest, which in turn will keep your download to the client small, and as fast as possible.

It may not seem like a huge deal, bug a gpx dataset for a single trail could be huge. Take a look at http://maps.thrca.com/westbranch.html for an example of a small dataset that generates a path AND points.

This is part of a project I was working on that takes a gpx file from a gps, loads it onto a map, and pushpins the waypoints that were added on the GPS. The other part not shown, loads a bunch of images from a camera, syncs up the timestamps and pushpins them onto the trail into the appropriate spot based on the timestamp.
Was This Post Helpful? 0
  • +
  • -

#11 compactbrain  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 35
  • Joined: 21-January 10

Re: Google maps

Posted 21 January 2012 - 05:02 PM

Would you have a better way of refreshing the map? If you look at my code I just clear the array before refreshing it. Also is it possible to call some php from js? I have a script that updates the database and I'd like that to run every second aswell
Thanks
  function addLatLng()
  {
    var path = poly.getPath();
        microAjax("genjson.php", function(data)
        {
            var json = JSON.parse(data);
            var points = json;
            for (var i = 0; i < points.length; i++)
            {
              var point = points[i];
              var latlng = new google.maps.LatLng(parseFloat(point.lat),parseFloat(point.lng));
              path.push(latlng);
            }
        });
	path.clear();//this here
	{setTimeout("addLatLng()",1000)};
   }


Was This Post Helpful? 0
  • +
  • -

#12 thrca  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 28
  • View blog
  • Posts: 65
  • Joined: 21-January 12

Re: Google maps

Posted 21 January 2012 - 06:44 PM

Considering your dataset can become quite large, I generally would advise against refreshing every second, unless it is extremely necessary for near real-time data (perhaps 5 or 10 seconds would be more appropriate?)

That being said, if you wanted to add points incrementally, you should be able to define the var path in the global scope, add a timestamp to your request to genjson, then return just the points that are new since the last timestamp and push them to the path. It would look something like the following pseudo-code.

var path = poly.getPath();
var ts; //set a timestamp
var keep_refreshing = true; //set to false at anytime to halt refresh
function addLatLng(ts){
  if(typeof(ts) === 'undefined')ts = 0;
  microAjax("genjson.php?ts="+ts, function(data){
    var json = JSON.parse(data);
    var points = json.points;
    ts = json.ts; //we sent this from php
    for (var i = 0; i < points.length; i++){
      var point = points[i];
      var latlng = new google.maps.LatLng(parseFloat(point.lat),parseFloat(point.lng));
      path.push(latlng);
    }
  });
  if(keep_refreshing)setTimeout('addLatLng()',5000);
}



Now, to support this incremental update, we need to make a couple changes to the code that gets the data...

<?php
require("dbinfo.php");
header('Content-Type: application/json');

$ts = (isset($_GET['ts']))? $_GET['ts'] : 0;

$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}

$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}

$sth = mysql_query("SELECT lat,lng FROM markers WHERE creation_timestamp>=".$ts);
$points = array();
while($r = mysql_fetch_assoc($sth)) {
    $points[] = $r;
}

$timestamp = strtotime("now");
$output = array("ts"=>$timestamp,"points"=>$points); //encode the new timestamp and points into the output array
echo json_encode($output);;
?>



This assumes you have an insertion timestamp in your database called 'creation_timestamp'
Was This Post Helpful? 1
  • +
  • -

#13 compactbrain  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 35
  • Joined: 21-January 10

Re: Google maps

Posted 21 January 2012 - 07:13 PM

I'll set that up now, its a much more efficient way to go about things. would you know about calling the php? I have a file refmySQL.php the retrieves data from a remote pc and updates the database with new coordinates
could i use something like xhtml.open(refmySQL.php)

Thanks

This post has been edited by compactbrain: 21 January 2012 - 07:16 PM

Was This Post Helpful? 0
  • +
  • -

#14 thrca  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 28
  • View blog
  • Posts: 65
  • Joined: 21-January 12

Re: Google maps

Posted 21 January 2012 - 07:31 PM

Do you have cron access to the server? Since php (and all websites, for that matter) are a client/server setup, it doesn't make much sense to use a client connection to perform the periodic polling to the device, but you could make a cronjob that calls 'php -q /path/to/some_poller_script.php' which would call it on the interval that you requested. If you are making socket connections, it has to run under the root crontab.

Doing this would ensure that the poller is run on the schedule, regardless of whether a client is connected or not.
Was This Post Helpful? 0
  • +
  • -

#15 thrca  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 28
  • View blog
  • Posts: 65
  • Joined: 21-January 12

Re: Google maps

Posted 21 January 2012 - 07:42 PM

I put a little more thought into the genjson.php side of that stuff I posted, and decided it would be better to use the timestamps from the db to eliminate cross-platform compatibility issues with the syntax and format of the timestamps in php vs in the database.. See as follows

<?php
require("dbinfo.php");
header('Content-Type: application/json');

$ts = (isset($_GET['ts']))? $_GET['ts'] : 0;

$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}

$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}

$sth = mysql_query("SELECT lat,lng,creation_timestamp FROM markers WHERE creation_timestamp>=".$ts." ORDER BY creation_timestamp ASC");
//add order by statement, so the records come out oldest first
//it may also be wise to set a LIMIT of like 50 or so, so that it will only download the first 50 points in the track since the latest one we have.. This way, if your track is large, it doesnt take forever to load, it will just load incrementally, 50 points every 5 seconds.. or 100, or whatever.
$points = array();
while($r = mysql_fetch_assoc($sth)) {
    $points[] = array('lat'=>$r['lat'],'lng'=>$r['lng']); //specify which cols, since we dont need timestamp included in the dataset
    $ts = $r['creation_timestamp']; //set to most recent records timestamp
}

$timestamp = strtotime("now");
$output = array("ts"=>$timestamp,"points"=>$points); //encode the new timestamp and points into the output array
echo json_encode($output);;
?>



I also did not sanitize the $_GET['ts'], as it was just a quick pseudocode off the top of my head.. You should always sanitize your input variables before using them in a query.

A quick and dirty way to do that would be in the query ...
 ... WHERE creation_timestamp>=".mysql_real_escape_string($ts)." ORDER BY ...


Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2