Sunday, November 1, 2015

How To Integrate Google Map API Using PHP mySQL examples scripts


Maps are perfect examples of modern web philosophy, visually representing data and also taking advantage of the mobile web by allowing sites and apps to be customized by location. Not every web application needs maps, but they can enhance many of them.
Just as it has with search, Google has all but cornered the market in online mapping. There are other players (Yahoo, Bing, etc), but the vast majority of online map users are using Google Maps, so if you are programming a map into your site or app, you can’t avoid working with Google.> The good news is, Google’s Maps API is actually quite user friendly and easy to integrate into a PHP / MySQL application. This lesson is going to walk you through using PHP and MySQL with Google Maps to create maps that are attractive, useful, and customizable.

Getting Started

For this tutorial, I’m going to assume that you have PHP and MySQL installed, and that you’ve done some basic programming with both. If you’re brand new to both programs, you can check out our Introduction to PHP and PHP Basics: MySQL tutorials to get up to speed.
The other thing that you’ll need to get started with Google Maps is a Google API key. This is a long alphanumeric code that allows you access to Google’s API code. To get an API key, go to this page. If you have a Google account (through GMail or another Google service) already, then it’s pretty much a one-click process.

Prepping Your Database for Mapping

In order to use PHP and MySQL to build dynamic maps for your application, you’ll need database tables to store the geographic information that will be displayed on the map. There are several ways to go about this, but here is an example that will work for our purposes. First, put the following code in a new PHP file, calledconnect.php:
1
2
3
4
5
6
7
<?php
  $con = new mysqli("localhost", "user", "password", "databasename");
  if($con->connect_errno > 0){
    die('Unable to connect to database [' . $con->connect_error . ']');
  }
?>
If you took our PHP Basics: MySQL tutorial (LINK), you’ll recognize this code as the same MySQL connection code that we used there. Replace the host, user, password, and databasename variables with the correct ones for your database, and your connection script should be good to go.
Next, start another new PHP file, and call this one create.php. This is where we’re going to set up our data tables to populate our map:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
  include 'connect.php';
   
  $createmaptable = 'CREATE TABLE IF NOT EXISTS maps (
  ID int AUTO_INCREMENT,
  PRIMARY KEY (ID),
  centerLat decimal (5,3),
      centerLong decimal (6,3),
      zoom  tinyint
  );';
  if(!$result = $con->query($createmaptable)){
    die('There was an error running the query [' . $con->error . ']');
  }
  $createmappointtable = 'CREATE TABLE IF NOT EXISTS mappoints (
  ID int AUTO_INCREMENT,
  PRIMARY KEY (ID),
      mapID int,
  pointLat decimal (5,3),
      pointLong decimal (6,3),
      pointText text
  );';
  if(!$result = $con->query($createmappointtable)){
    die('There was an error running the query [' . $con->error . ']');
  }
?>
We’re using a MySQL data type in these tables that we didn’t cover in the PHP Basics tutorial on MySQL, namely the decimal type. When declaring a decimal field in our database tables, we set two attributes: the total number of decimal places and the number of places after the decimal point. So, we create the field for the latitude of our map’s center with centerLat decimal (5,3), because latitudes can only range from -90 to 90 degrees (2 places), and we want a precision of three decimal places after the decimal point. Since longitudes can range over 100 or under -100, we need to add an extra place for the longitude fields.

Adding Some Data

Now we have two new database tables, one to hold data on maps (lat and long of center point and zoom level) and one to hold individual mapping points (again, a lat and long for each, and a text description). Now we need to populate these tables with some test data so we have something to work with.
Add the following code to the end of create.php, inside the closing ?> tag:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
$maps = array(
  array(1, 45.52, -122.682, 9),
  array(2, -33.98, 18.424, 10),
  array(3, 57.48, -4.225, 12)
);
$mappoints = array(
  array(1, 45.249, -122.897, "Champoeg State Park"),
  array(1, 45.374, -121.696, "Mount Hood"),
  array(2, -33.807, 18.366, "Robben Island"),
  array(2, -33.903, 18.411, "Cape Town Stadium"),
  array(3, 57.481, -4.225, "Inverness Bus Station"),
  array(3, 57.476, -4.226, "Inverness Castle"),
  array(3, 57.487, -4.139, "The Barn Church")
);
foreach ($maps as $ind) {
  $newline = "INSERT INTO maps
    (ID, centerLat, centerLong, zoom)
    VALUES ($ind[0], $ind[1], $ind[2], $ind[3])";
  if(!$insertmap = $con->query($newline)){
    die('There was an error running the query [' . $con->error . ']');
  }
}
foreach ($mappoints as $indpt) {
  $newline = "INSERT INTO mappoints
    (mapID, pointLat, pointLong, pointText)
    VALUES ($indpt[0], $indpt[1], $indpt[2], '$indpt[3]')";
  if(!$insertmap = $con->query($newline)){
    die('There was an error running the query [' . $con->error . ']');
  }
}
This script creates two arrays, one holding three rows of map data, the other holding seven map points, then enters them into their respective data tables. Run all of create.php by loading the page in your browser. You’ll notice that if you try to load the page twice, it will create an error, since the IDs for each map are already set. This is because of the PRIMARY KEY we set on the ID column of the table maps, which ensures that each row has a unique ID.

Your First Map

All right. We have tables, we have data. Now it’s time to build our first map. Enter the following code into a new file, called map.php:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
  include 'connect.php';
  $apikey = "your_key_here";
  $id = $_GET['id'];
  $lat = 0;
  $long = 0;
  $zoom = 8;
  $findmap = "SELECT centerLat, centerLong, zoom FROM maps WHERE ID = $id";
  if(!$result = $con->query($findmap)){
     die('There was an error running the query [' . $con->error . ']');
  } else {
    $row = $result->fetch_assoc();
    $lat = $row['centerLat'];
    $long = $row['centerLong'];
    $zoom = $row['zoom'];
  }  
?><!DOCTYPE html>
<html>
  <head>
    <meta name="viewport"
        content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map-canvas { height: 100% }
    </style>
    <script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=
          <?php echo $apikey; ?>&sensor=false">
    </script>
    <script type="text/javascript">
      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(<?php echo $lat.', '.$long; ?>),
          zoom: <?php echo $zoom; ?>
        };
        var map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
      }
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map-canvas"/>
  </body>
</html>
Make sure you replace the value of the $apikey variable with your own API key.
The HTML portion of this page (from <!DOCTYPE to </html>) is provided by Google, and is the simplest code possible for displaying a basic map. The PHP we’ve added at the top of the script queries your database, selects the map details to match whatever map ID has been specified, and sets them into variables for the map to use. Notice that if you load the page map.php, you will get an error, since the page requires the id variable to be set. Try loading map.php?id=1, and a map of Portland, OR should display. Try map.php?id=2 and map.php?id=3 for maps of two of my other favorite cities in the world.

Setting Map Points

Raw maps are great if you just want to show your site’s visitors a specific part of the world, but Google Maps are infinitely more useful with map points added. Add this bit of code into map.php right after mapOptions);, and the map points that we set in our database table will show up in each of our example maps:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
  $getpoints = "SELECT pointLat, pointLong, pointText
      FROM mappoints WHERE mapID = $id";
  if(!$result = $con->query($getpoints)){
    die('There was an error running the query
        [' . $con->error . ']');
  } else {
    while ($row = $result->fetch_assoc()) {
      echo '  var myLatlng1 = new google.maps.LatLng('.
          $row[pointLat].', '.$row[pointLong].');
  var marker1 = new google.maps.Marker({
    position: myLatlng1,
    map: map,
    title:"'.$row[pointText].'"
  });';
    }
  }
?>
Take a look again at all three example maps. One of them should look pretty much like this:
php_mysql_map
The map points will show up as red pins, and when you hover your cursor over each one, the name of the place will appear. Congratulations. You’ve just made a dynamic Google Map!
Ref - http://www.syntaxxx.com/php-and-mysql-working-with-google-maps/

project proposal about school
project proposal about feeding program
project proposal about waste management
project proposal about environment
project proposal about business
project proposal about bullying
project proposal about education
project proposal about school canteen
project proposal about health
project proposal about tree planting
after project proposal
project proposal for school
project proposal at school
project proposal at
project proposal on women's empowerment
project proposal on livelihood
project proposal on cassava production
project proposal by student
project proposal for bank loan
project proposal for hotel
project proposal for website
project proposal for hotel management system
project proposal for library management system
project proposal for new business
project proposal for software development
project proposal for pharmacy management system
project proposal for road construction
project proposal from
project proposal in sinhala
project proposal in tamil
project proposal in sri lanka
project proposal in school
project proposal in barangay
project proposal in tagalog
project proposal in reading and writing
project proposal in community
project proposal in hindi
example of project proposal inside the school
what is a project proposal like
project proposal of comfort room
project proposal of school
project proposal of tree planting
project proposal of poultry farming
project proposal of feeding program
project proposal of covered court
project proposal of ngo
project proposal of ssg
project proposal of school canteen
project proposal of barangay
project proposal sign off
project proposal on vegetable production pdf
project proposal on occupational health and safety
project proposal on food processing
project proposal on malnutrition
project proposal outline
project proposal out
project proposal for out of school youth in the philippines
project proposal for out of school youth
project proposal layout
sample project proposal for out of school youth
project proposal about overpopulation
past project proposal
project proposal on post harvest technology
project proposal for post doc
project pre proposal
project proposal to school
project proposal to a company
project proposal to get funding
project proposal to government
project proposal to client sample
project proposal to improve customer service
project proposal to bank loan
project proposal to dst
project proposal to drdo
project proposal to management
project proposal under rkvy
project proposal under dst
project proposal under ugc
preliminary project proposal under imprint-2
preliminary project proposal under imprint-2 serb
project proposal write up
project proposal clean up drive
project proposal write up template
project proposal follow up letter
project proposal write up pdf
project proposal follow up email
project proposal coastal clean up
project proposal and feasibility study
project proposal and business plan
project proposal and concept paper
project and proposal
project proposal vs project charter
project proposal vs project plan
project proposal vs research proposal
project proposal vs business plan
project proposal vs business case
project proposal vs business proposal
project proposal vs feasibility study
project proposal and reports
project proposal vs sow
project proposal and concept note
project proposal with budget
project proposal with timeline
project proposal with example
project proposal with gantt chart
project proposal with rationale
project proposal with methodology

project proposal with

No comments:

Post a Comment