谷歌地图和放大器;如何通过从PHP页面到另一个变量时,不包含在PHP页面 [英] Google maps & how pass variable from php page to another, when that php page is not included

查看:225
本文介绍了谷歌地图和放大器;如何通过从PHP页面到另一个变量时,不包含在PHP页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的例子:使用PHP / MySQL的与谷歌地图 https://developers.google.com/maps/articles/phpsqlajax_v3

我知道这个教程之前已经介绍了很多,但我无法找到我要找的答案,并希望有人能够帮助。

我想展现一个谷歌地图与标志。每个标记是一本书的图标。书是按类别组织(我把它叫做类型在我的数据库)。这个想法是,用户就可以选择他们想要的书的类别,然后只有这些书将在地图上显示。

我的问题是我不能让表单中选择工作,类型变量需要从index.php来的页面phpsqlajax_genxml2.php过去了,为了使数据库中进行查询。

我的问题是 - 如何让PHP变量$类型的phpsqlajax_genxml2.php页

的phpsqlajax_genxml2.php页中不包括index.php页面,但有一个downloadUrl功能: downloadUrl(phpsqlajax_genxml2.php功能(数据)

下面是我的文件完全。在此先感谢

的index.php

 < PHP
    //从URL参数
    $型= $ _GET [型];
    ?>


    <!DOCTYPE HTML>
  < HEAD>
    < META NAME =视CONTENT =初始规模= 1.0,用户可扩展性=无/>
    < META HTTP-当量=内容类型内容=text / html的;字符集= UTF-8/>
    <冠军>的PHP / MySQL和放大器;谷歌地图为例< /标题>
    <脚本类型=文/ JavaScript的SRC =htt​​ps://maps.googleapis.com/maps/api/js>< / SCRIPT>
    <脚本类型=文/ JavaScript的>
    //<![CDATA [

    VAR customIcons = {
      神秘谋杀案:{
        图标:http://labs.google.com/ridefinder/images/mm_20_black.png
      },
      旅游指南:{
        图标:http://labs.google.com/ridefinder/images/mm_20_gray.png
      },
      演义:{
        图标:http://labs.google.com/ridefinder/images/mm_20_purple.png
      },
      '短篇故事': {
        图标:http://labs.google.com/ridefinder/images/mm_20_green.png
      },
      惊悚:{
        图标:http://labs.google.com/ridefinder/images/mm_20_red.png
      },
      '喜剧': {
        图标:http://labs.google.com/ridefinder/images/mm_20_yellow.png
      },
      '图画小说': {
        图标:http://labs.google.com/ridefinder/images/mm_20_white.png
      },
      '讽刺': {
        图标:http://labs.google.com/ridefinder/images/mm_20_brown.png
      }

    };
< / SCRIPT>

<脚本类型=文/ JavaScript的>

//检查浏览器支持W3C的地理位置API

如果(navigator.geolocation){
  navigator.geolocation.getCurrentPosition(successFunction,errorFunction);
  } 其他 {
  警报('地理位置需要这个页面,但你的浏览器不放大器;者;吨支持它的浏览器,做,如Opera 10.60试试吧。');
}

功能errorFunction(位置){
  警报(错误!);
}

//如果成功地理位置然后绘制的地图,在地图上显示我的COORDS,拉的图标

功能successFunction(位置){
  VAR纬度= position.coords.latitude;
  VAR LNG = position.coords.longitude;
        VAR地图=新google.maps.Map(的document.getElementById(图),
        {
        中心:新google.maps.LatLng(纬度,经度)
        变焦:13,
        mapTypeId:路线图
        });

        VAR信息窗口=新google.maps.InfoWindow;

      // SQL到XML文件
      //downloadUrl("phpsqlajax_genxml2.php?type=+型,功能(数据){
      downloadUrl(phpsqlajax_genxml2.php功能(数据){
        VAR XML = data.responseXML;
        VAR的标记= xml.documentElement.getElementsByTagName(标记);
        对于(VAR I = 0; I< markers.length;我++){
          VAR名称=标记[I] .getAttribute(姓名);
          VAR地址=标记[I] .getAttribute(地址);
          VAR类型=标志物[I] .getAttribute(类);
          VAR点=新google.maps.LatLng(
              parseFloat(标记[I] .getAttribute(土地增值税)),
              parseFloat(标记物[I] .getAttribute(LNG)));
          VAR HTML =< B>中+姓名+< / B>< BR />中+地址+< BR />中+< I>中+类型+< / I>中;
          VAR图标= customIcons [类型] || {};
          VAR的标记=新google.maps.Marker({
            地图:地图,
            位置:点,
            图标:icon.icon
          });
          bindInfoWindow(标记,地图,信息窗口,HTML);
        }
      });
    }

    功能bindInfoWindow(标记,地图,信息窗口,HTML){
      google.maps.event.addListener(标记,'点击',函数(){
        infoWindow.setContent(HTML);
        infoWindow.open(地图,标记);
      });
    }

    功能downloadUrl(URL,回调){
      VAR请求= window.ActiveXObject?
          新的ActiveXObject(Microsoft.XMLHTTP):
          新XMLHtt prequest;

      request.onreadystatechange =功能(){
        如果(request.readyState == 4){
          request.onreadystatechange = doNothing;
          回调(要求,request.status);
        }
      };

      request.open(GET,URL,真正的);
      request.send(空);
    }

    功能doNothing(){}

    //]]≥

  < / SCRIPT>

  < /头>

<身体的onload =successFunction(位置)>

< D​​IV ID =地图的风格=宽度:500px的;高度:400像素>< / DIV>

<形式的行动=< PHP $ _PHP_SELF>?方法=GET>
<选择名称=输入>
  <期权价值=神秘谋杀案>神秘谋杀案和LT; /选项>
  <期权价值=旅游指南>旅行指南和LT; /选项>
  <期权价值=浪漫>浪漫< /选项>
  <期权价值=短篇小说>短篇小说< /选项>
  <期权价值=颤栗>惊悚< /选项>
  <期权价值=喜剧>喜剧< /选项>
  <期权价值=绘图小说>图表小说< /选项>
  <期权价值=讽刺>讽刺< /选项>
< /选择>
<输入类型=提交值=提交/>
< /形式GT;

< /身体GT;

< / HTML>
 

phpsqlajax_genxml2.php

 < PHP
//从URL参数
$型= $ _GET [型];

包括(INC / DB_connect.php);

//使用PHP的回声输出XML

功能parseToXML($ htmlStr)
{
$ xmlStr = str_replace函数('<','&放大器; LT;',$ htmlStr);
$ xmlStr = str_replace函数('>','&放大器; GT;',$ xmlStr);
$ xmlStr = str_replace函数('','和; QUOT;',$ xmlStr);
$ xmlStr = str_replace函数(','和;#39;',$ xmlStr);
$ xmlStr = str_replace函数(&放大器;,&放大器;放大器;',$ xmlStr);
返回$ xmlStr;
}


//打开一个到MySQL服务器的连接
$连接=的mysql_connect(本地主机,$的用户名,密码$)
如果(!$连接){
  死亡(未连接:mysql_error());
}

//设置活动的MySQL数据库
$ db_selected = mysql_select_db($数据库,$连接);
如果(!$ db_selected)
{
  死亡(可以\'吨使用DB:mysql_error());
}

//选择在标记表中的所有行
// $查询=SELECT * FROM`markers` WHERE 1;
$查询=SELECT * FROM`markers` WHERE`type` ='$类型';
$结果= mysql_query($查询)或死亡(mysql_error());

标题(内容类型:文本/ XML);

//开始XML文件,回声父节点
回声'<标记>';

//遍历对每个行,打印XML节点
而($行= @mysql_fetch_assoc($结果))
{
  //增加来XML文档节点
  回声'<标记;
  回声NAME ='parseToXML($行['名称'])。'';
  回声地址='parseToXML($行['地址'])。'';
  回声'叻='$行['纬度']。'';
  回声'LNG ='$行['LNG']。'';
  回声类型='$行['类型']。'';
  回声/>';
}

//结束XML文件
回声'< /标记>';

?>
 

解决方案

所以,如果你想从一个PHP文件到另一个传递数据,你必须在这种情况下两个选择,cookie和session:

的Cookie:

  //其中第1页
$ _COOKIE ['varname的'] = $ var_value;

//在第2页
$ var_value = $ _COOKIE ['varname的'];
 

会话:

  //在第1页
$ _SESSION ['varname的'] = $ var_value;

//在第2页
$ var_value = $ _SESSION ['varname的'];
 

会话和饼干之间最大的区别是变量的值,如果你正在使用的会话,并在客户端上,如果你使用的cookie存储在服务器上。我想不出用饼干代替会议,除非你想要的数据会话之间持续存在,但即使如此,它可能是更好的将其存储在一个数据库,并根据用户名或ID检索任何好的理由。

修改

有支持的一个方法,你可以通过该变量在JQuery的电话是这样的:

在你的第一个文件:

 的jQuery('#图)的负载('Firstfile.php型=<?PHP的echo($型);?>')。
 

在你的第二个文件

  $型= $ _GET ['类型'];
 

给这一个镜头!

从<一提到href="http://stackoverflow.com/questions/18723585/passing-php-variable-from-one-file-to-another">Passing PHP变量从一个文件到另一个?

I’m working on the example: "Using PHP/MySQL with Google Maps" https://developers.google.com/maps/articles/phpsqlajax_v3

I know this tutorial has been covered a lot before but I can’t find the answer I’m looking for, and hope someone can help.

I’m trying to show a Google Map with markers. Each marker is a book icon. Books are organised by category (I’ve called it "type" in my database). The idea is that users can select which category of book they want, and then only these books will be shown on the map.

My problem is I can’t get the FORM select to work, the "type" variable needs to be passed from the index.php to the page phpsqlajax_genxml2.php, in order for the database to be interrogated.

My question is - how do i get the php variable $type to the phpsqlajax_genxml2.php page?

The phpsqlajax_genxml2.php page is not included in the index.php page, but there is a downloadUrl function: downloadUrl("phpsqlajax_genxml2.php", function(data)

Here are my files in full. Thanks in advance

index.php

    <?php
    // Get parameters from URL
    $type = $_GET["type"];
    ?>


    <!DOCTYPE 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>PHP/MySQL & Google Maps Example</title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
    <script type="text/javascript">
    //<![CDATA[

    var customIcons = {
      'Murder Mystery': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_black.png'
      },
      'Travel Guide': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_gray.png'
      },
      'Romance': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_purple.png'
      },
      'Short Story': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
      },
      'Thriller': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
      },
      'Comedy': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png'
      },
      'Graphic Novel': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_white.png'
      },
      'Satire': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_brown.png'
      }

    };
</script>

<script type="text/javascript">

//Check if browser supports W3C Geolocation API

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
  } else {
  alert('Geolocation is required for this page, but your browser doesn&apos;t support it. Try it with a browser that does, such as Opera 10.60.');
}

function errorFunction(position) {
  alert('Error!');
}

//If successful geolocation then draw the map, show my coords on the map, and pull in the icons

function successFunction(position) {
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
        var map = new google.maps.Map(document.getElementById("map"), 
        {
        center: new google.maps.LatLng(lat, lng),
        zoom: 13,
        mapTypeId: 'roadmap'
        });

        var infoWindow = new google.maps.InfoWindow;

      // SQL to XML file
      //downloadUrl("phpsqlajax_genxml2.php?type=" + type, function(data) {
      downloadUrl("phpsqlajax_genxml2.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 + "<br/>" + "<i>" + type + "</i>";
          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon
          });
          bindInfoWindow(marker, map, infoWindow, html);
        }
      });
    }

    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(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>

  </head>

<body onload="successFunction(position)">

<div id="map" style="width: 500px; height: 400px"></div>

<form action="<?php $_PHP_SELF ?>" method="GET">
<select name="type">
  <option value="Murder Mystery">Murder Mystery</option>
  <option value="Travel Guide">Travel Guide</option>
  <option value="Romance">Romance</option>
  <option value="Short Story">Short Story</option>
  <option value="Thriller">Thriller</option>
  <option value="Comedy">Comedy</option>
  <option value="Graphic Novel">Graphic Novel</option>
  <option value="Satire">Satire</option>
</select>
<input type="submit" value="Submit" />
</form>

</body>

</html>

phpsqlajax_genxml2.php

<?php
// Get parameters from URL
$type = $_GET["type"];

include ("inc/DB_connect.php");

//Using PHP's echo to Output XML

function parseToXML($htmlStr) 
{ 
$xmlStr=str_replace('<','&lt;',$htmlStr); 
$xmlStr=str_replace('>','&gt;',$xmlStr); 
$xmlStr=str_replace('"','&quot;',$xmlStr); 
$xmlStr=str_replace("'",'&#39;',$xmlStr); 
$xmlStr=str_replace("&",'&amp;',$xmlStr); 
return $xmlStr; 
}


// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}

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

// Select all the rows in the markers table
//$query = "SELECT * FROM `markers` WHERE 1";
$query = "SELECT * FROM `markers` WHERE `type` = '$type'";
$result = mysql_query($query) or die(mysql_error());

header("Content-type: text/xml");

// Start XML file, echo parent node
echo '<markers>';

// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result))
{
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}

// End XML file
echo '</markers>';

?>

解决方案

So if you want to pass data from one PHP file to another, You have two options in this case, Cookies and Sessions:

Cookie:

//One page 1
$_COOKIE['varname'] = $var_value;

//On page 2
$var_value = $_COOKIE['varname'];

Session:

//On page 1
$_SESSION['varname'] = $var_value;

//On page 2
$var_value = $_SESSION['varname'];

The big difference between sessions and cookies are that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.

EDIT

There is one more method supported where you can pass that variable in your JQuery call like this:

In your first file:

jQuery('#map').load('Firstfile.php?type=<?php echo($type);?>');

In your second file

$type = $_GET['type'];

Give this one a shot!!

Referred from Passing php variable from one file to another?

这篇关于谷歌地图和放大器;如何通过从PHP页面到另一个变量时,不包含在PHP页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆