Display data from postgis over google maps - google-maps-api-3

I am working on a project where i am using postgres/postgis and asp.net with c# connected with google maps api v3.
My issue is that i would like to be able to display spatial data ex: points of interests from the db on the map.
Is there exists any library that will do the conversion from postgis to a format like .kml?

There is a wrapper called as_kmldoc for PostGIS' ST_AsKML function, you could give it a try. It is not really sophisticated but could suit your needs.
SELECT as_kmldoc(osgb_location, NAME, code) FROM wunderground_stations;

You can use ST_AsKML but then you still need to create the KML string using that data. Here is the full function (in php), which creates kml with world borders from mysql database.
public function generateWorld() {
$tolerance = 20000;
$select = $this->_db->select()
->from ( array( 'w' => 'world_borders'),
array ('cat', 'cntry_name', 'geom' => "ST_AsKML(transform(ST_SimplifyPreserveTopology(transform(w.the_geom, 2249), " . $tolerance . "),4326))"));
$result = $this->_db->fetchAll($select);
$countriesByCat = array();
foreach ($result as $r) {
if ($countriesByCat[$r['cat']] === null) $countriesByCat[$r['cat']] = array();
array_push($countriesByCat[$r['cat']], $r);
}
$kml = '<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
<name>borders</name>';
for($i = 0; $i < count($countriesByCat); $i++) {
$kml .= '<Placemark><name>'.$countriesByCat[$i][0]['cntry_name'].'</name>';
if (count($countriesByCat[$i]) > 1) {
$kml .= '<MultiGeometry>';
foreach ($countriesByCat[$i] as $geom) {
$kml .= $geom['geom'];
}
$kml .= '</MultiGeometry>';
}
else {
$kml .= $countriesByCat[$i][0]['geom'];
}
$kml .= '</Placemark>';
}
$kml .= '</Document></kml>';
echo $kml;
}

Related

Cron Job In Custom Plugin Not Working In Wordpress

I have added this cronjob in my WordPress custom plugin but when I run the function manually it is working but through cronjob, it is not working. Here is my code! All the plugin files are loaded correctly not showing any error.
Can anybody help me to sort this out! I have tried a lot but still, it is not working.
<?php
if (!wp_next_scheduled('generateusedcarsfeed'))
{
wp_schedule_event(time() , '5mins', 'generateusedcarsfeed');
}
add_action('generateusedcarsfeed', 'generate_used_car_feed');
if (!wp_next_scheduled('generateusedcarsfeed'))
{
wp_schedule_event(time() , '5mins', 'generateusedcarsfeed');
}
add_action('generateusedcarsfeed', 'generate_used_car_feed');
// Getting all used cars with all data
function generate_used_car_feed(){
try{
// for opening the csv file
$file = fopen('all-cars-feed.csv', 'r');
fwrite($file, '');
$loop = new WP_Query($args);
chmod('all-cars-feed.csv', 0777);
// for creating array from csv file
$file="all-cars-feed.csv";
$csv= file_get_contents($file);
$array = array_map("str_getcsv", explode("\n", $csv));
$json_csv_arr = json_encode($array);
$my_array_csv = json_decode($json_csv_arr, true);
// for getting used car list from databse, only take publish used car
global $wpdb;
$query = "SELECT wp_postmeta.post_id, wp_postmeta.meta_value FROM wp_postmeta
INNER JOIN wp_posts ON wp_posts.id = wp_postmeta.post_id WHERE meta_key = 'car_registration_number'
AND post_status = 'publish'";
$result = $wpdb->get_results($query);
$json_reg_num = json_encode($result);
$my_array = json_decode($json_reg_num, true);
print_r($my_array);
foreach ($my_array as $value) {
$car_reg_array = $value['meta_value'];
$Post_id= $value['post_id'];
$isTrue=true;
$ch = fopen("all-cars-feed.csv", "r");
while($row = fgetcsv($ch)) {
if (in_array($car_reg_array, $row)) {
echo 'found</hr>';
$isTrue=false;
}
}
if($isTrue)
{
$wpdb->query(
'UPDATE '.$wpdb->prefix.'posts SET post_status = "trash"
WHERE ID = "'.$Post_id.'"');
}
}
//fclose($file);
}
catch(\Exception $e)
{
$txt = 'Message: ' . $e->getMessage();
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($fileLoger, $txt);
fclose($fileLoger);
}
}
I wonder if this 5mins interval really exists in your setup. Try adding this code to make sure this actually exists (if it does already, it won't break stuff):
function add_custom_cron_schedules($schedules){
if (!isset($schedules["5mins"])) {
$schedules["5min"] = array(
'interval' => 5*60,
'display' => __('Every 5 minutes'));
}
return $schedules;
}
add_filter('cron_schedules','add_custom_cron_schedules');
If you want to retrieve currently available schedules, you can also use wp_get_schedules() and check out if a certain key (like '5mins') exists.

Add class to drupal body

How can I add term id of all terms related to a node, to that node body class in drupal site?
For example, A node named stackoverflow is tagged with four terms
term1
term2
term3
term4
term5
I want to add these classed to node body class...
article-term-(term1tid)
article-term-(term2tid)
article-term-(term3tid)
article-term-(term4tid)
article-term-(term5tid)
These are pages I want to change their class names:
عکس نوزاد
عکس نوزاد
کاردستی
سوپ ساده
داستان برای کودک
کاردستی
leymannx code is really complete and fine.
But it does not contains all terms of a node.
I wrote this code and i wish it will be useful for you.
function YOURTHEME_preprocess_html(&$variables) {
if (arg(0) == 'node' && is_numeric(arg(1))) {
$node = node_load(arg(1));
$results = stackoverflow_taxonomy_node_get_terms($node);
if (is_array($results)) {
foreach ($results as $item) {
$variables['classes_array'][] = "article-term-" . $item->tid;
}
}
}
}
There is a function named ""stackoverflow_taxonomy_node_get_terms"" that returns all terms attached to a node.
function stackoverflow_taxonomy_node_get_terms($node, $key = 'tid'){
static $terms;
if (!isset($terms[$node->vid][$key])) {
$query = db_select('taxonomy_index', 'r');
$t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
$v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
$query->fields($t_alias);
$query->condition("r.nid", $node->nid);
$result = $query->execute();
$terms[$node->vid][$key] = array();
foreach ($result as $term) {
$terms[$node->vid][$key][$term->$key] = $term;
}
}
return $terms[$node->vid][$key];
}
i wish this code could be the best.
write all of this codes in template.php file in your theme.
if you want just some nodes have class name, add replace this part of code.
> if (arg(0) == 'node' && is_numeric(arg(1)) && ( arg(1)==X || arg(1)==Y
> ) ) {
As #P1ratRuleZZZ already pointed out template_preprocess_html (implemented from your sub-theme's template.php file) is the function to add body classes.
Thing is, that within this function, you need to load the actual node object first, then get the values of that term reference field, to finally add them as classes to the body tag.
Replace MYTHEME and field_MYFIELD with your names.
/**
* Implements template_preprocess_html().
*/
function MYTHEME_preprocess_html(&$variables) {
// Get the node.
if ($node = menu_get_object()) {
// Check node type.
if ($node->type === 'article') {
// Get taxonomy terms.
$terms = field_get_items('node', $node, 'field_MYFIELD');
foreach ($terms as $term) {
// Add body class.
$variables['classes_array'][] = 'article-term-' . $term['tid'];
}
}
}
}
Try to use template_preprocess_html()
this is in your theme's template.php file:
YOURTHEMENAME_preprocess_html(&$variables) {
$term_id = arg(1); // For example, or use some &drupal_static() to store a value while preprocessing from module
$variables['classes_array'][] = 'article-term-' . $term_id;
}
So as you can see it you shoud change template_ to your themename_ first

Doctrine entity to CSV

Since few hours i try to convert doctrine2 entities to csv.
My idea was to convert doctrine entities to array with (in my repository ):
return $query->getArrayResult();
And after, convert this array to csv.
But the convertion array to csv don't work because there are DateTime Object in my field....
Does anybody have a simple way to convert doctrine entities to CSV ?
(ps : I tried to search by myself on many post without success, so sorry to disturb you :-( )
To prevent getting errors while converting to Datetime you will have to do it manually. Iterate across all objects and format the datetime using the following for the DateTime objects:
$date->format('Y-m-d H:i:s');
For example you could do the following:
$csv = "";
foreach ($result as $item)
{
foreach($item as $element)
{
if($element instanceof DateTime)
$csv .= $element->format('Y-m-d H:i:s'); //Converts the Datetime to string for the given format
else
$csv .= $element;
$csv .= ",";
}
$csv .= "\r\n"; //Adds new line
}
echo $csv;

How to use the $content variable within a module in Drupal 7, Ubercart 3

I'm running the latest versions of Drupal 7 & Ubercart 3. I'm trying to capture date from the $content variable for use within a module. Specifically I am trying to capture data from a custom product field and display that data inline certain product attributes/options.
The point of this is to create a custom description for each attribute for each product.
It seems the $content variable is not available from uc_attribute.module. Using $content['field_original_size']; returns: undefined variable content . If I use the render function I am returned no errors nor data. Here is what I have so far:
function theme_uc_attribute_option($variables) {
$original_size = render($content['field_original_size']);
if($variables['option'] == 'Original'){
$output = $variables['option'];
$output .= ', ' . $original_size;
if ($variables['price']) {
$output .= ', ' . $variables['price'];
}
}
else{
$output = $variables['option'];
if ($variables['price']) {
$output .= ', ' . $variables['price'];
}
}
return $output;
}
It seems that th easiest way to do this, may be with the token_replace() function, so heres what I am trying now but does not work. There are no errors, but the token does not get replaced.
function theme_uc_attribute_option($variables) {
if($variables['option'] == 'Original'){
$output = $variables['option'];
if ($variables['price']) {
$output .= ', ' . '[node:field-medium]';
$output .= ', ' . $variables['price'];
token_replace($output);
}
}
else{
$output = $variables['option'];
if ($variables['price']) {
$output .= ', ' . $variables['price'];
}
}
return $output;
}
You could print out the $variables, and see if what you need is somewhere in there.
I think it's because you didn't declare your function using a reference to $variables. I believe it should be called as function theme_uc_attribute_option(&$variables) {}. That tells PHP to send a reference to the variable instead of the value of the variable. When the value is sent, any changes to it are local only. If a reference is used, the changes make their way back to the variable. See the PHP Manual for details. I just noticed how old this is.

how to print output in drupal hook_block

How to Print the output, if i written in WHILE SNIPPET in the function ,
Below is my snippet, i want print retrieved result ,
i tried echo ,
but we should not use echo in drupal, and drupal set message function for debug purpose ,
So how to print my output in this example ,
function node_example_block($op='list',$delta=0){
switch($op){
case "list":
$block[0]['info'] = t('THIS IS EXAMPLE NODE EXAMPLE ');
return $block;
case "view":
$block['subject'] = "THIS MY FIRST SAMPLE BLOCK";
$block['content'] = drupal_get_form('display_node_title');
return $block;
}
}
function display_node_title(){
$result = db_query("SELECT * FROM node");
$output = '';
while ($obj = db_fetch_object ($result)){
$output .= $obj->title;
}
//drupal_set_message($output);
}
You're having display_node_title get passed through drupal_get_form, but display_node_title isn't a form function. If it were, it'd be constructing a $form array via the Form API and return $form; at the end.
Change:
$block['content'] = drupal_get_form('display_node_title');
to:
$block['content'] = display_node_title();
and add:
return $output;
to the end of your display_node_title() function.

Resources