CodeIgniter Forums
Passing Results from SQL to Google Maps API in CodeIgniter - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Passing Results from SQL to Google Maps API in CodeIgniter (/showthread.php?tid=30732)

Pages: 1 2


Passing Results from SQL to Google Maps API in CodeIgniter - El Forum - 05-24-2010

[eluser]jshultz[/eluser]
I'm hoping to use Google Maps on my site.

My addresses are stored in a DB. I’m pulling up a page where the information is all dynamic. For example: mysite.com/site/business/5 (where 5 is the id of the business).

Let’s say I do a query like this:

Code:
function addressForMap($id) {
    $this->db->select('b.id, b.busaddress, b.buscity, b.buszip');
    $this->db->from('business as b');
    $this->db->where('b.id', $id);
}

How can I output the info to the Google Maps API correctly so that it displays the map appropriately?

The Google Maps API interface I'm using takes the results like this: $marker['address'] = 'Crescent Park, Palo Alto'; within the controller before the map is created.


Passing Results from SQL to Google Maps API in CodeIgniter - El Forum - 05-24-2010

[eluser]pickupman[/eluser]
This should do it:
[code]
//Model
function addressForMap($id) {
$this->db->select('b.id, b.busaddress, b.buscity, b.buszip');
$this->db->from('business as b');
$this->db->where('b.id', $id);
$query = $this->db->get();

if($query->num_rows() > 0)
return $query->row();

return FALSE;
}
//Controller
$address = $this->your_model->addressForMap($id); //Get result row

$marker['address'] = ''; //Set default if row is not returned
if(count($address) > 0){
$marker['address'] = $address->busaddress .' '.$address->buscity .', '. $address->buszip;
}


Passing Results from SQL to Google Maps API in CodeIgniter - El Forum - 05-25-2010

[eluser]jshultz[/eluser]
I updated the model to what you showed:

Code:
function addressForMap($id) {
    $this->db->select('b.id, b.busaddress, b.buscity, b.buszip');
    $this->db->from('business as b');
    $this->db->where('b.id', $id);
    return $this->db->get();
    if($query->num_rows() > 0)
      return $query->row();

  return FALSE;
}

and my controller now looks like this:

Code:
function business($id)
    {
        $this->load->model('Business_model');
        $this->load->model('Gallery_model');
        
        $this->load->library('googlemaps');
        $config['apikey'] = 'my-super-secret-google-api-key-is-here';
        $marker = array();
        $address = $this->Business_model->addressForMap($id); //Get result row
        
        $marker['address'] = ''; //Set default if row is not returned
            if(count($address) > 0){
              $marker['address'] = $address->busaddress .' '.$address->buscity .', '. $address->buszip;
            }
        $this->googlemaps->add_marker($marker);
        $this->googlemaps->initialize($config);
        $data['map'] = $this->googlemaps->create_map();
        
        $data['photos'] = $this->Gallery_model->get_images_from_db($id);
        $data['business']     = $this->Business_model->businessQuery($id);
        $data['user_id']    = $this->tank_auth->get_user_id();
        $data['username']    = $this->tank_auth->get_username();
        $data['page_title'] = 'Welcome To Jerome - Largest Ghost Town in America';
        $data['page'] = 'business_view'; // pass the actual view to use as a parameter
        $this->load->view('container',$data);
    }
But i'm getting the following errors:

A PHP Error was encountered

Severity: Notice

Message: Undefined property: CI_DB_mysql_result::$busaddress

Filename: controllers/site.php

Line Number: 52

A PHP Error was encountered

Severity: Notice

Message: Undefined property: CI_DB_mysql_result::$buscity

Filename: controllers/site.php

Line Number: 52

A PHP Error was encountered

Severity: Notice

Message: Undefined property: CI_DB_mysql_result::$buszip

Filename: controllers/site.php

Line Number: 52


line 52 is this: $marker['address'] = $address->busaddress .' '.$address->buscity .', '. $address->buszip;


Passing Results from SQL to Google Maps API in CodeIgniter - El Forum - 05-25-2010

[eluser]SitesByJoe[/eluser]
I went a totally different direction and just put some PHP conditional logic in my view within my javascript that generates the maps. Seemed real simple for me. I wasn't aware of a googlemaps library for CI - is it generating all the javascript before loading the view?

Interesting.


Passing Results from SQL to Google Maps API in CodeIgniter - El Forum - 05-25-2010

[eluser]jshultz[/eluser]
It does the geocodeing supposedly. it's running api v2 and not v3 yet. but my needs are simple.

I just needed something that would geocode the address and show the map on the fly as soon as the page was loaded. no clicky button things going on and stuff.


Passing Results from SQL to Google Maps API in CodeIgniter - El Forum - 05-25-2010

[eluser]SitesByJoe[/eluser]
Here's what I've done: (I use the jmaps plugin for jquery FYI)

In my template view I have code like this in the head of the document: (inside my script tag)

Code:
<?php if ( $map_display == 'city' || $map_display == 'property') : ?>                            
    var url = '/map/coordinates.php';
    $.get(url, {'address': '<?=$address?>', 'key': '<?=$this->config->item('google_map_key')?>'}, function(data) {
            var json = eval("(" + data + ")");
            if (json.coordinates.lat != 0) {
                    $('#map').jmap({ center: [json.coordinates.lat, json.coordinates.lng], zoom: <?=$zoom_lvl?> });
            }
    });                
<?php else : ?>                
    var url = '/map/coordinates.php';
    var key = '<?=$this->config->item('google_map_key')?>';
    $('#map').jmap({ zoom: <?=$zoom_lvl?> });                    
<?php endif; ?>

The code that the url variable refers to is: (this is where the geocaching is done)

Code:
<?php
// this is a very unelegant method of getting map markers
// but it works for the moment - until more than 10000 happen in one day

header('Cache-Control: no-cache');
header('Pragma: no-cache');

// build the google url to ping for coordinates
$address = str_replace(' ', '+', $_GET['address']);
$key = $_GET['key'];
$url="http://maps.google.com/maps/geo?q=" . str_replace(" ", "+", $address) . "&output=csv&key;=" . $key;
// send the request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
$remote_content = curl_exec($curl);
curl_close ($curl);
// scrape the returned csv
$coordinates = split(',', $remote_content);
$lat = $coordinates[2];
$lng = $coordinates[3];
// return some json
$data = '
{"coordinates":
        {
            "lat": "' . $lat . '",
            "lng": "' . $lng . '",
            "address": "' . str_replace('+', ' ', $address) . '"
        }
}';
echo $data;

?>

As you can see this is just a basic PHP file, not a controller or anything. This is also an old solution, but it works well. If you're gather the same addresses repeatedly it'd be a good idea to database the coordinates to save your google requests from being too numerous.

Hope this helps!


Passing Results from SQL to Google Maps API in CodeIgniter - El Forum - 05-25-2010

[eluser]SitesByJoe[/eluser]
Oh yeah, I also set my map defaults (zoom, api key etc) in my custom config file.


Passing Results from SQL to Google Maps API in CodeIgniter - El Forum - 05-25-2010

[eluser]jshultz[/eluser]
That's pretty cool. If I can't get this API thing to work I may have to try that.


Passing Results from SQL to Google Maps API in CodeIgniter - El Forum - 05-25-2010

[eluser]yannyannyann[/eluser]
Thanks Joe.

I started converting to a controler... might help you :

Code:
[removed]
                    <?php
                    $zoom_lvl = 5; ?>
                    
                        var url = '<?php echo URL ?>map/index/MY_API_KEY_HERE/MY_ADDRESS_HERE';
                        console.log(url);
                        $.get(url, function(data) {
                                var json = eval("(" + data + ")");
                                if (json.coordinates.lat != 0) {
                                        $('#map').jmap({ center: [json.coordinates.lat, json.coordinates.lng], zoom: <?=$zoom_lvl?> });
                                }
                        });                                
                    [removed]


Code:
<?php
class Map extends Controller {

    function Map()
    {
        parent::Controller();
    }

    function index($key, $address)
    {

        // this is a very unelegant method of getting map markers
        // but it works for the moment - until more than 10000 happen in one day
        header('Cache-Control: no-cache');
        header('Pragma: no-cache');

        // build the google url to ping for coordinates
        $address = str_replace(' ', '+', $address);
        $url="http://maps.google.com/maps/geo?q=" . str_replace(" ", "+", $address) . "&output=csv&key;=" . $key;
        // send the request
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
        $remote_content = curl_exec($curl);
        curl_close ($curl);
        // scrape the returned csv
        $coordinates = split(',', $remote_content);
        $lat = $coordinates[2];
        $lng = $coordinates[3];
        // return some json
        $data = '
        {"coordinates":
                {
                    "lat": "' . $lat . '",
                    "lng": "' . $lng . '",
                    "address": "' . str_replace('+', ' ', $address) . '"
                }
        }';
        echo $data;
    }
}



Passing Results from SQL to Google Maps API in CodeIgniter - El Forum - 05-25-2010

[eluser]jshultz[/eluser]
here's an update. I changed the model to this:

Code:
function addressForMap($id) {
    $this->db->select('b.id, b.busaddress, b.buscity, b.buszip');
    $this->db->from('business as b');
    $this->db->where('b.id', $id);
    $this->db->limit(1);
    $query = $this->db->get();
    if($query->num_rows() > 0)
      return $query->row();
}

and the controller to this:

Code:
function business($id)
    {
        $this->load->model('Business_model');
        $this->load->model('Gallery_model');
        
        $this->load->library('googlemaps');
        $config['apikey'] = 'ABQIAAAAG3I2PYsLZmCKSGh9gQyFPxS05A1zuuWdQK96RRjHJj9eRVu7XhSneKyBDAldwoHgcW1AGR-OKebmzw';
        $marker = array();
        $busaddress = $this->Business_model->addressForMap($id); //Get result row
        $marker['address'] = $busaddress->busaddress .' '.$busaddress->buscity .', '. $busaddress->buszip;

        $this->googlemaps->add_marker($marker);
        $this->googlemaps->initialize($config);
        $data['map'] = $this->googlemaps->create_map();
        
        
        $data['photos'] = $this->Gallery_model->get_images_from_db($id);
        $data['business']     = $this->Business_model->businessQuery($id);
        $data['user_id']    = $this->tank_auth->get_user_id();
        $data['username']    = $this->tank_auth->get_username();
        $data['page_title'] = 'Welcome To Jerome - Largest Ghost Town in America';
        $data['page'] = 'business_view'; // pass the actual view to use as a parameter
        $this->load->view('container',$data);
    }

I'm not getting any errors, but the address isn't updating.