Welcome, Guest
Username: Password: Remember me

TOPIC: How to Create a Map of Locations

How to Create a Map of Locations 4 months 3 weeks ago #101907

I've developed a method of mapping locations derived from LimeSurvey map responses and thought I would share.

This is a multi-step process.

1. For the mapping to work within your survey, even at the question level, you will need to get authorization for your api. Follow these instructions:

rimpygarg.wordpress.com/2012/06/06/how-t...rvice-in-limesurvey/


2. Alter your main survey db table (depending on the db table prefix you used, should look like limesurvey_123456)
a. Using phpMyAdmin, add the fields lng and lat to your table, along with an identifier field that will appear in your info balloon (you can add more if you want to have, but these three are essential)

i) IMMEDIATELY FOLLOWING the id field, add field lon (field type decimal(10,7))
ii) IMMEDIATELY FOLLOWING the lon field, add field lat (field type decimal(10,7))
iii) IMMEDIATELY FOLLOWING the lat field, add the field siteInfo (field type varchar(150))
iv) add as many fields as you want to show up in the info balloon.

3. Now that your table is modified so that your php scripts can use data from it, you will need to update the table so that these fields are populated with data retrieved from LimeSurvey.

We will create three files to do this, and you will also want to upload two .js files (code below). One connects with your db, one updates your db, and one paints your map. Update red text to match your own needs:

i)
vConnect.php
<?php  
// Place db hostname here.  
$db_host =[color=#ff0000] "limesurvey.db.123456.hostedresource.com[/color]"; 
// Place the username for the MySQL database here 
$db_username = [color=#ff0000] "limesurveyUsername[/color]";  
// Place the password for the MySQL database here 
$db_pass = [color=#ff0000] "password[/color]";  
// Place the name for the MySQL database here 
$db_name = [color=#ff0000] "limeSurveyDB[/color]"; 

// Run the actual connection here  
mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("$db_name") or die ("no database");              
?>

ii)
update.php

Using phpMyAdmin, find the row in your table that holds your lat/lon information. You may have to take your survey live, if you have not yet done this, and put in some dummy information so that you can identify the correct field. The field data will look like this:

34.08721315914823;-118.2044792175293;Los Angeles;CA;US;90031

In my demo case, the fieldname "123456X2X48" holds geographical information, and the 1234562X12 field holds site info. We will pull data out of both of these fields to populate our table, but the mapping interface will not accept the json data in the geo field, and we might as well put in the siteInfo data if we have to modify our table anyway. So in the code below modify the highlighted fields to match your table.
<?php
		include "vConnect.php";
$query = "SELECT * FROM [color=#ff0000]limesurvey_123456[/color] ORDER BY id";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
		$resultGeo= explode(";", $row["[color=#ff0000]123456X2X48[/color]"]);
		$lat = $resultGeo[0];
		$lon = $resultGeo[1];
		$city = $resultGeo[2];
		$state = $resultGeo[3];
		$countryCode = $resultGeo[4];
		$zip = $resultGeo[5];
        $getid = $row['id'];
        $siteInfo = $row['[color=#ff0000]1234562X12[/color]'];
 
        $query = mysql_query("UPDATE [color=#ff0000]limesurvey_123456[/color] 
                        SET siteInfo = '$siteInfo ', lat = '$lat', lon = '$lon', city = '$city', state = '$state', countryCode = '$countryCode', zip = '$zip'
                   WHERE id = '$getid'");
        }
?>

Now you are ready to paint your map. You will do that

iii)
map.php
<html>
    <head>
    <script type='text/javascript' src='js/jquery-1.6.2.min.js'></script>
    <script type='text/javascript' src='js/jquery-ui-1.8.14.custom.min.js'></script>
    <style>
 
        BODY {font-family : Verdana,Arial,Helvetica,sans-serif; color: #000000; font-size : 13px ; }
 
        #map_canvas { width:100%; height: 100%; z-index: 0; }
    </style>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false" /></script>
    <script type='text/javascript'>
 
    //This javascript will load when the page loads.
    jQuery(document).ready( function($){
 
            //Initialize the Google Maps
            var geocoder;
            var map;
            var markersArray = [];
            var infos = [];
 
            geocoder = new google.maps.Geocoder();
            var myOptions = {
                  zoom: 9,
                  mapTypeId: google.maps.MapTypeId.HYBRID
                }
            //Load the Map into the map_canvas div
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
 
            //Initialize a variable that the auto-size the map to whatever you are plotting
            var bounds = new google.maps.LatLngBounds();
            //Initialize the encoded string       
            var encodedString;
            //Initialize the array that will hold the contents of the split string
            var stringArray = [];
            //Get the value of the encoded string from the hidden input
            encodedString = document.getElementById("encodedString").value;
            //Split the encoded string into an array the separates each location
            stringArray = encodedString.split("****");
 
            var x;
            for (x = 0; x < stringArray.length; x = x + 1)
            {
                var addressDetails = [];
                var marker;
                //Separate each field
                addressDetails = stringArray[x].split("&&&");
                //Load the lat, long data
                var lat = new google.maps.LatLng(addressDetails[2], addressDetails[1]);
                //Create a new marker and info window
                marker = new google.maps.Marker({
                    map: map,
                    position: lat,
                    //Content is what will show up in the info window
                    content: addressDetails[0]
                });
                //Pushing the markers into an array so that it's easier to manage them
                markersArray.push(marker);
                google.maps.event.addListener( marker, 'click', function () {
                    closeInfos();
                    var info = new google.maps.InfoWindow({content: this.content});
                    //On click the map will load the info window
                    info.open(map,this);
                    infos[0]=info;
                });
               //Extends the boundaries of the map to include this new location
               bounds.extend(lat);
            }
            //Takes all the lat, longs in the bounds variable and autosizes the map
            map.fitBounds(bounds);
 
            //Manages the info windows
            function closeInfos(){
           if(infos.length > 0){
              infos[0].set("marker",null);
              infos[0].close();
              infos.length = 0;
           }
            }
 
    });
    </script>
 
    </head>
    <body>
    <div id='input'>
 
        <?php
		include "vConnect.php";
		include "update.php";
 
 
//Initialize your first couple variables
$encodedString = ""; //This is the string that will hold all your location data
$x = 0; //This is a trigger to keep the string tidy
 
//Now we do a simple query to the database
$result = mysql_query("SELECT * FROM `[color=#ff0000]limesurvey_123456[/color]`");
 
//Multiple rows are returned
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
    //This is to keep an empty first or last line from forming, when the string is split
    if ( $x == 0 )
    {
         $separator = "";
    }
    else
    {
         //Each row in the database is separated in the string by four *'s
         $separator = "****";
    }
    //Saving to the String, each variable is separated by three &'s
    $encodedString = $encodedString.$separator.
    "<p class='content'>
	<br><b>Lon:</b> ".$row[1].
    "<br><b>Lat:</b> ".$row[2].
    "<br><b>SiteInfo: </b>".$row[3].
    "</p>&&&".$row[1]."&&&".$row[2];
    $x = $x + 1;
} ?>
        <input type="hidden" id="encodedString" name="encodedString" value="<?php echo $encodedString; ?>" />
    </div>
    <div id="map_canvas"></div>
    </body>
</html>

iv)
jquery-1.6.2.min.js

Don't be frightened by this code. You don't need to touch it. Just copy it, save it as jquery-1.6.2.min.js and then upload it to your js directory on your server.

I uploaded the file, but it was not accessible from this post, and so was useless.

You can download jquery-1.6.2.min.js here: www.macrostash.com/wp-content/plugins/jquery-1.6.2.min.js

v)
jquery-ui-1.8.14.custom.min.js

I tried to include the code here, but the upload file was not accessible, and the code itself was truncated. Again, download the file, save it somewhere, then upload to your js directory on your server.

www.macrostash.com/wp-content/plugins/jq...1.8.14.custom.min.js

I think that's it. Please update or refine as you wish.

Limesurvey rules.
Last Edit: 4 months 3 weeks ago by velvetmonster. Reason: incorrect numbering
The administrator has disabled public write access.

How to Create a Map of Locations 4 months 3 weeks ago #101909

Text formatted as code in this post did not correctly translate color information. Wherever you see the text
[color=#ff0000]code[/color]

within code, remove both
[color=#ff0000]

and
[/color]

tags and change the information between these tags to meet your own needs.
Last Edit: 4 months 3 weeks ago by velvetmonster.
The administrator has disabled public write access.
Moderators: ITEd
Time to create page: 0.439 seconds
Donation Image