gmaps.js add marker from PHP array

烂漫一生 提交于 2019-12-12 06:05:55

问题


I am trying to add a marker to my gmaps.js map. The long. and lat. values are stored in a database, which I select using a PHP Script.

Once fetched, both of the long. and lat. values are stored in an array, under the variable $data.

I wanted to use json_encode($data); in order to pass the variables, however I would have had to change the header to a json application, I have already echoed some PHP onto the page, therefore this is unfeasable.

I have now tried echoing the json_encode into the jQuery function using an $.each loop, however it has been unsuccessful, as not every entry retrieved by the database will have a marker.

What is the best solution, to get an ID, long. and lat. value for max 10 records, pass this to a jQuery function to position on a map?


回答1:


As not all records have markers, youll have to parse the results so that only the required data gets passed to your js function. I'd create a php array and add the marker I'd, lat,long etc... Under the same key:

$markersarray = array ()
foreach($records as $record){

  if($record['lat'] != ““){
    $markersarray[] = array(
         'id'=>$record['id'], 
         'lat'=>$record['lat'],
         'long'=>$record['long']
    );
  }
}

$markersjson = json_encode($markersarray);

Then you could use a hidden input to store the encoded json string which then could be passed into your js.

 <input id="markersjson" type="hidden" value="<?php echo $markersjson; ?>"/>

in your js function

var markersdata = $('#markersjson').val();

You may need to parse this value to an object

var obj = jQuery.parseJSON(markersdata);

then use a $.each to loop through your obj



来源:https://stackoverflow.com/questions/34476280/gmaps-js-add-marker-from-php-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!