简体   繁体   English

从JSON PHP将标记加载到Google Map

[英]Load markers to google map from json php

I am trying to load some markers to google maps for my webpage. 我正在尝试为我的网页的Google地图加载一些标记。

I have all markers in a DB and I take them by a php script. 我在数据库中有所有标记,并通过php脚本使用它们。 This script print all data in DB as json. 该脚本将DB中的所有数据打印为json。 Something like this: 像这样:

<?php
   require_once("phpsqlajax_dbinfo.php"); //info for DB connection


   // 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 coordY, coordX FROM contenedor WHERE peso = 12";
  $result = mysql_query($query);
  if (!$result) {
    die('Invalid query: ' . mysql_error());
  }



  $x = 0;
  while ($row = @mysql_fetch_assoc($result)){
    $data[$x] = array("lat" => $row['coordY'], "lng" => $row['coordX']);
    $x++;
 }
 echo json_encode($data);
 ?>

My json file should look like this: [{"lat":"A","lng":"B"},{"lat":"C","lng":"D"},{"lat":"E","lng":"F"}] //Characters are lat and long... 我的json文件应如下所示:[{“ lat”:“ A”,“ lng”:“ B”},{“ lat”:“ C”,“ lng”:“ D”},{“ lat”: “ E”,“ lng”:“ F”}]] //字符长而经...

After that, in other file (my index.html) I create map, like: 之后,在其他文件(我的index.html)中创建地图,例如:

 var map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(new GLatLng(X, Y), 13); //X and Y are my lat and long
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
 ...

I want to make a function called addMarket to load all my markers. 我想创建一个名为addMarket的函数来加载所有标记。 But I am not able to get the info from that file from javascript. 但是我无法从javascript的文件中获取信息。 I though something like this: 我虽然是这样的:

for (var i = 0;i < file.length; i += 1) {
    var lat = file[i].lat;
    var lon = file[i].lng;
    addMarker(lat,lon);
};

function addMarker(lat,lng){
var latlng = new google.maps.LatLng(lat,lng);  
var marker = new google.maps.Marker({position: latlng, map: map});

But I don't kow how I should read values or get all of them in an array. 但是我不知道如何读取值或将所有值都放入数组中。

Any idea? 任何想法?

Other question I have is: is it possible to upload markers when I am watching the map? 我的另一个问题是:观看地图时是否可以上传标记? For example, if one of my markers change during watching, I want to get the new value (for example, changing color..) I have addMarker function inside initialize function, should I get it outside? 例如,如果我的一个标记在观看过程中发生更改,我想获取新值(例如,更改颜色。)我在initialize函数内部具有addMarker函数,是否应该在外部使用它?

thanks! 谢谢!

您必须给json一个名称,以使其可以被JS访问,例如:

echo 'file='.json_encode($data),';';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM