简体   繁体   English

将地图位置信息从PHP传递到javascript以与Google Maps v3 api一起使用

[英]Passing Map Location information from PHP to javascript for use with Google maps v3 api

I have a bunch of latitude & longitude markers stored in MySQL which I can retrieve simply with PHP. 我在MySQL中存储了一堆纬度和经度标记,可以使用PHP轻松检索它们。 I interact with the Google maps API v3 with Javascript and load several markers in an array as a dummy, each one has a infowindow as well. 我使用Javascript与Google Maps API v3进行了交互,并在数组中加载了多个标记作为虚拟标记,每个标记都有一个信息窗口。

What would people recommend as the best method of handing the data in MySQL to a javascript object/array for use with the google maps api v3. 人们会推荐什么作为将MySQL中的数据处理到javascript对象/数组以与google maps api v3一起使用的最佳方法。

Get the values from DB, by using PHP while loop and store the values in a variable as below 通过使用PHP while循环从DB获取值,并将值存储在变量中,如下所示

$location .= '['. $row['latitude'] . ',' . $row['longitude'] . ',"' . $row['city'] . '","' . $row['state'] . '"],' ;

In Javascript, assign the PHP variable to a Javascript variable as below. 在Javascript中,将PHP变量分配给Javascript变量,如下所示。

var locations = [<?php echo isset($location)?$location:''; ?>];
var len = locations.length;
for (i = 0; i < len; i++) {  
   var image = 'GIVE HERE THE PATH OF IMAGE';
   marker = new google.maps.Marker({
     position: new google.maps.LatLng(locations[i][1], locations[i][2]),
     map: map,
     icon: image
   });
   google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
     return function() {              
    infowindow.setContent(content);
    infowindow.open(map, marker);
 }
   })(marker, i));
}

The above code will give multiple markers and as well as infobox for each marker in the map. 上面的代码将为地图提供多个标记以及每个标记的信息框。

If you have a PhP array containing a lot of markers, for example: 如果您的PhP数组包含很多标记,例如:

Array
(
    [0] => Array
           (
           ["lat"]=> <value>
           ["lng"]=> <value>
           ["info"]=> <value>
           )
    [1] => Array
           (
           ["lat"]=> <value>
           ["lng"]=> <value>
           ["info"]=> <value>
           )
    [2] => ...
    [3] => ...
)

using JSON is a good solution as : 使用JSON是一个很好的解决方案,例如:

  1. it will save you the trouble of escaping the values stored in it 这将避免您转义存储在其中的值的麻烦
  2. You can easily retrieve the same data structure in javascript (using JSON.parse() if you need to) and use it create your markers. 您可以轻松地在javascript中检索相同的数据结构(如果需要,可以使用JSON.parse())并使用它创建标记。

To convert your array to JSON from PhP: 要将数组从PhP转换为JSON:

json_encode($myMarkersArray, JSON_NUMERIC_CHECK)

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

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