Skip to content

Instantly share code, notes, and snippets.

@ajitStephen
Last active June 21, 2021 04:04
Show Gist options
  • Select an option

  • Save ajitStephen/f0ecba333a034d86efe2cf1912a6c7c1 to your computer and use it in GitHub Desktop.

Select an option

Save ajitStephen/f0ecba333a034d86efe2cf1912a6c7c1 to your computer and use it in GitHub Desktop.
mojo / plugin:API DATA (functions.php)
<?php
$GMAPS_KEY = '';
function debug($unknown){
if(gettype($unkown)){
echo '<pre>';
print_r($unknown);
echo '</pre>';
return;
}
echo '<pre>';
echo $unknown;
echo '</pre>';
}
function saveLocation($zipid){
global $wpdb;
try{
if(empty($zipid)){
// DEFAULTS: 9940 belgium [51.141145 / 3.7264042]
$latitude = 51.141145;
$longitude = 3.7264042;
} else {
$searchAddr = "belgium+".$zipid;
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?key='.$GMAPS_KEY.'&address='.$searchAddr.'&sensor=false');
$output= json_decode($geocode);
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
if(empty($latitude) || empty($longitude)){
throw new Exception('Lat Lng returned empty from Google Maps.');
}
}
$fields = array(
'data_id' => $vacancy->id,
'city'=>$city,
'zipid'=>$zipid,
'lat'=>$latitude,
'lng'=>$longitude,
'description'=>$description
);
$args= wp_parse_args( $fields);
$result = $wpdb->insert( $table_name, $args);
return ["lat"=>$latitude,"lng"=>$longitude];
}catch(Exception $e){
debug($e->getMessage());
}
}
function updateVacancyLocation($vacancyId, $lat_lng){
global $wpdb;
try{
$vacancytable= $wpdb->prefix . 'vacancies';
$vacancyitems = $wpdb->get_results( 'SELECT data FROM ' .$vacancytable .' where data_id=' .$vacancyId);
$data=json_decode($vacancyitems[0]->data);
$data->{"lat_lng"} = $lat_lng;
$updatedData = array('data'=>json_encode($data));
$vfield= wp_parse_args( $updatedData);
$wpdb->update($vacancytable, $vfield, array('data_id' => $vacancyId));
return true;
}catch(Exception $e){
debug($e->getMessage());
}
}
function addLatLngToVacancies($vacancies){
global $wpdb;
$table_name = $wpdb->prefix . 'vacancylocation';
$errors = [];
foreach($vacancies as $vacancy){
try{
$city=$vacancy->placeofemploymentzipcode->city;
$zipid=$vacancy->placeofemploymentzipcode->zipid;
$description=$vacancy->placeofemploymentzipcode->province->description;
$items = $wpdb->get_results('SELECT * FROM ' .$table_name .' where zipid=' .$zipid);
$item=(!empty($items))?$items[0]:null;
$lat_lng = [];
if(empty($item)){
$lat_lng = saveLocation($zipid);
} else {
$lat_lng = ["lat"=>$item->lat, "lng"=>$item->lng];
}
updateVacancyLocation($vacancy->id, $lat_lng);
} catch(Exception $e){
array_push($errors,[$vacancy->id=>$e]);
}
}
if(count($errors)>0){
debug($errors);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment