Google autocomplete to a specific city - php

I already create a geocode api on google console. I have a search box input with the google autocomplete in my site and I would like to set a specific city to my geocode api and integrate it in my web app. The city is: toulouse, Country: France.
When the customer type his address on the search box, I want it to only search all address in the city of toulouse, based on the center of toulouse with covered distance of 20 km.
Here is my code based on the file Function.php
public function geoCoding($lat='',$lng='')
{
$protocol = isset($_SERVER["https"]) ? 'https' : 'http';
if ($protocol=="http"){
$url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=".$lat.",".$lng."&sensor=true";
} else $url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=".$lat.",".$lng."&sensor=true";
$google_geo_api_key=getOptionA('google_geo_api_key');
if (!empty($google_geo_api_key)){
$url=$url."&key=".urlencode($google_geo_api_key);
}
$data = #file_get_contents($url);
if (!empty($data)){
$result = json_decode($data,true);
//dump($result);
if (!isset($result['results'])){
return false;
}
if (is_array($result['results']) && count($result['results'])>=2){
$location = array();
foreach ($result['results'][0]['address_components'] as $component) {
switch ($component['types']) {
case in_array('street_number', $component['types']):
$location['street_number'] = $component['long_name'];
break;
case in_array('route', $component['types']):
$location['street'] = $component['long_name'];
break;
case in_array('neighborhood', $component['types']):
$location['street2'] = $component['long_name'];
break;
case in_array('sublocality', $component['types']):
$location['sublocality'] = $component['long_name'];
break;
case in_array('locality', $component['types']):
$location['locality'] = $component['long_name'];
break;
case in_array('administrative_area_level_2', $component['types']):
$location['admin_2'] = $component['long_name'];
break;
case in_array('administrative_area_level_1', $component['types']):
$location['admin_1'] = $component['long_name'];
break;
case in_array('postal_code', $component['types']):
$location['postal_code'] = $component['long_name'];
break;
case in_array('country', $component['types']):
$location['country'] = $component['long_name'];
$location['country_code'] = $component['short_name'];
break;
}
}
return $location;
}
}
return false;
}

Your description sounds like you are using the Search Box widget in the Maps JavaScript API's Places library, but your code only shows use of reverse geocoding in the Geocoding API web service.
Since I think only the former makes sense, I'll venture you'll be interested in the following feature requests that would allow you to restrict autocomplete to a city:
Issue 8606: places bound restrict
Issue 4433: allow componentRestrictions to filter same components as the geocoding API service
For now, the options I know of are:
Set the Search box bounds to those of the city (which you can get from Geocoding API) and rely on the widget to prefer (not restrict) suggestions within those bounds, or
Build your own widget using AutocompleteService.getQueryPredictions() and do your own after-the-fact filtering to remove suggestions, but that would be very tricky because the name of the city will not necessarily always be part of the suggestion.

Related

PHP Switch with simple strings not working

$url = $_SERVER['REQUEST_URI'];
$url = basename($url).PHP_EOL;
switch ($url) {
case 'digital-marketing-and-seo':
$new_url = "Digital Marketing & SEO";
break;
case 'websites-digital-destinations':
$new_url = "Websites & Digital Destinations";
break;
case 'brand-identity-evolution':
$new_url = "Brand Identity & Evolution";
break;
case 'strategy-consulting':
$new_url = "Strategy & Consulting";
break;
case 'government-universities':
$new_url = "Government & Universities";
break;
case 'hospitality-travel':
$new_url = "Hospitality & Travel";
break;
case 'architecture-engineering':
$new_url = "Architecture & Engineering";
break;
case 'wine-spirits':
$new_url = "Wine & Spirits";
break;
default:
$new_url = '';
echo 'default derp';
}
So I have this block of code and it will not work for me. The url can say exactly what is in the case and it will default. I'm trying to get url structures to build out a shortcode and I need it to match what is entered.
I determined that if I enter just add a variable for a string for $url = 'brand-identity-evolution'; The switch works. I made sure it's a string with is_string function and can't figure out why this isn't working.
You added a PHP_EOL at the end of the URL, so all of your cases will fail because you're not checking for that. Remove your PHP_EOL and you'll be fine.

Change web banner image based upon country of the visitor

I have a small website (using HTML, PHP and MySQL), and would like to display a specific banner image according to the country of the visitor. Each country has a different banner image.
I have searched Google for solutions and found quite some API's (such as HostIP) that allow to return the country based upon the IP address. That's nice, but I could not find how to implement it for my purpose to make the image switch according to the country...
I have no developer knowledge. Can anyone help me out?
Get Geo-IP Information
Requests a geo-IP-server (netip.de) to check, returns where an IP is located (host, state, country, town).
<?php
$ip='94.219.40.96';
print_r(geoCheckIP($ip));
//Array ( [domain] => dslb-094-219-040-096.pools.arcor-ip.net [country] => DE - Germany [state] => Hessen [town] => Erzhausen )
//Get an array with geoip-infodata
function geoCheckIP($ip)
{
//check, if the provided ip is valid
if(!filter_var($ip, FILTER_VALIDATE_IP))
{
throw new InvalidArgumentException("IP is not valid");
}
//contact ip-server
$response=#file_get_contents('http://www.netip.de/search?query='.$ip);
if (empty($response))
{
throw new InvalidArgumentException("Error contacting Geo-IP-Server");
}
//Array containing all regex-patterns necessary to extract ip-geoinfo from page
$patterns=array();
$patterns["domain"] = '#Domain: (.*?) #i';
$patterns["country"] = '#Country: (.*?) #i';
$patterns["state"] = '#State/Region: (.*?)<br#i';
$patterns["town"] = '#City: (.*?)<br#i';
//Array where results will be stored
$ipInfo=array();
//check response from ipserver for above patterns
foreach ($patterns as $key => $pattern)
{
//store the result in array
$ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';
}
return $ipInfo;
}
?>
to complete the anwer of Avinash, is this the right solution to switch image based upon country?
function switchImage($var) {
switch ($var)
{
case "United states":
$source = '/images/US.png';
$class = 'myClass';
$alt = 'myAlt';
break;
case "United Kingdom":
$source = '/images/UK.png';
$class = 'myClass';
$alt = 'myAlt';
break;
.
.
.
default:
return "Default"; //default case
}
}

how to get image location from database using ID

I am working on my website using wordpress to view and change cover for user by clicking on photo and then redirect him for example to process.php?pid=12
I am using
switch($GetPicId)
{
So I can't add more pic I but now I have script to upload pic using database, and I wanna to get id and pic location from by using database
First this is the upload script
and this is switch code
$GetPicId = $_GET["pid"]; // Picture ID from Index page
$PicLocation ='';
/*
Users do not need to know original location of image.
I think it's better to get image location from database using ID.
for demo here i'am using PHP switch.
*/
switch($GetPicId)
{
case 1:
$PicLocation = 'cover_pics/cover1.jpg';
break;
case 2:
$PicLocation = 'cover_pics/cover2.jpg';
break;
case 3:
$PicLocation = 'cover_pics/cover3.jpg';
break;
case 4:
$PicLocation = 'cover_pics/cover4.jpg';
break;
case 5:
$PicLocation = 'cover_pics/cover5.jpg';
break;
case 6:
$PicLocation = 'cover_pics/cover6.jpg';
break;
case 7:
$PicLocation = 'cover_pics/cover7.jpg';
break;
case 8:
$PicLocation = 'cover_pics/cover8.jpg';
break;
case 9:
$PicLocation = 'cover_pics/cover9.jpg';
break;
case 10:
$PicLocation = 'cover_pics/cover10.jpg';
break;
case 11:
$PicLocation = 'cover_pics/cover11.jpg';
break;
default:
header('Location: ' . $homeurl);
break;
}
Just Try
$GetPicId = $_GET["pid"]; // Picture ID from Index page
$sql=mysql_query("SELECT piclocation FROM tableName WHERE pid=$GetPicId") or die(mysql_error());
$res=mysql_fetch_array($sql);
$PicLocation = $res['piclocation '];
Use this to get attachment url ..Your cover images are uploaded in media right??
Then try this
<?php wp_get_attachment_url( $id ); ?>
it will become something like this
$GetPicId = $_GET["pid"]; // Picture ID from Index page
$PicLocation =wp_get_attachment_url( $GetPicId);

API key for multiple domain script, google map V2

could any one check why my script below is not working please?
<script src="http://maps.google.com/maps?file=api&v=2.x&key=
<?php
$this->googleMapsApiKey = $this->getValueFromDB("google", "googleMapsApiKey");
if ($_SERVER['HTTP_HOST']=='www.ABC.info') {
$this->googleMapsApiKey = "Googlemap-keys";
} elseif ($_SERVER['HTTP_HOST']=='www.CBA.com') {
$this->googleMapsApiKey = "Googlemap-keys";
}
?>" type="text/javascript"></script>
Thanks a lot!!
You can avoid this whole problem: Maps API keys now support multiple domains (and you can edit authorised domains at any time). See Obtaining an API key for more details.
I totally agree with Wrikken, it does not seem that you echoed the variable during the process. Maybe this approach would help:
<?php
print '<script src="http://maps.google.com/maps?file=api&v=2.x&key=';
$this->googleMapsApiKey = $this->getValueFromDB("google", "googleMapsApiKey");
switch ($_SERVER['HTTP_HOST'])
{
//Specific for a domain, but I think that the default handles it against your DB automatically
//case 'www.ABC.info' : $this->googleMapsApiKey = "Googlemap-keys";
// break;
//Same here
// case 'www.CBA.com': $this->googleMapsApiKey = "Googlemap-keys";
// break;
default: $this->googleMapsApiKey = "Googlemap-keys";
}
echo "$this->googleMapsApiKey type=\"text/javascript\"></script>";
?>

Few Google Checkout Questions

I am planning to integrate a Google Checkout payment system on a social networking website. The idea is that members can buy "tokens" for real money (which are sort of the website currency) and then they can buy access to some extra content on the website etc.
What I want to do is create a Google Checkout button that takes a member to the checkout page where he pays with his credit or debit card. What I want is the Google Checkout to notify notify my server whether the purchase of tokens was successful (if the credit/debit card was charged) so I can update the local database.
The website is coded in PHP/MySQL.
I have downloaded the sample PHP code from here: code.google.com/p/google-checkout-php-sample-code/wiki/Documentation
I know how to create a Google checkout button and I have also placed the responsehandlerdemo.php file on my server. This is the file the Google Checkout is supposed to send response to (of course I set the path to the file in Google merchant account).
Now in the response handler file there is a switch block with several case statements. Which one means that the payment was successful and I can add tokens to the member account in the local database?
switch ($root) {
case "request-received": {
break;
}
case "error": {
break;
}
case "diagnosis": {
break;
}
case "checkout-redirect": {
break;
}
case "merchant-calculation-callback": {
// Create the results and send it
$merchant_calc = new GoogleMerchantCalculations($currency);
// Loop through the list of address ids from the callback
$addresses = get_arr_result($data[$root]['calculate']['addresses']['anonymous-address']);
foreach($addresses as $curr_address) {
$curr_id = $curr_address['id'];
$country = $curr_address['country-code']['VALUE'];
$city = $curr_address['city']['VALUE'];
$region = $curr_address['region']['VALUE'];
$postal_code = $curr_address['postal-code']['VALUE'];
// Loop through each shipping method if merchant-calculated shipping
// support is to be provided
if(isset($data[$root]['calculate']['shipping'])) {
$shipping = get_arr_result($data[$root]['calculate']['shipping']['method']);
foreach($shipping as $curr_ship) {
$name = $curr_ship['name'];
//Compute the price for this shipping method and address id
$price = 12; // Modify this to get the actual price
$shippable = "true"; // Modify this as required
$merchant_result = new GoogleResult($curr_id);
$merchant_result->SetShippingDetails($name, $price, $shippable);
if($data[$root]['calculate']['tax']['VALUE'] == "true") {
//Compute tax for this address id and shipping type
$amount = 15; // Modify this to the actual tax value
$merchant_result->SetTaxDetails($amount);
}
if(isset($data[$root]['calculate']['merchant-code-strings']
['merchant-code-string'])) {
$codes = get_arr_result($data[$root]['calculate']['merchant-code-strings']
['merchant-code-string']);
foreach($codes as $curr_code) {
//Update this data as required to set whether the coupon is valid, the code and the amount
$coupons = new GoogleCoupons("true", $curr_code['code'], 5, "test2");
$merchant_result->AddCoupons($coupons);
}
}
$merchant_calc->AddResult($merchant_result);
}
} else {
$merchant_result = new GoogleResult($curr_id);
if($data[$root]['calculate']['tax']['VALUE'] == "true") {
//Compute tax for this address id and shipping type
$amount = 15; // Modify this to the actual tax value
$merchant_result->SetTaxDetails($amount);
}
$codes = get_arr_result($data[$root]['calculate']['merchant-code-strings']
['merchant-code-string']);
foreach($codes as $curr_code) {
//Update this data as required to set whether the coupon is valid, the code and the amount
$coupons = new GoogleCoupons("true", $curr_code['code'], 5, "test2");
$merchant_result->AddCoupons($coupons);
}
$merchant_calc->AddResult($merchant_result);
}
}
$Gresponse->ProcessMerchantCalculations($merchant_calc);
break;
}
case "new-order-notification": {
$Gresponse->SendAck();
break;
}
case "order-state-change-notification": {
$Gresponse->SendAck();
$new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
$new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];
switch($new_financial_state) {
case 'REVIEWING': {
break;
}
case 'CHARGEABLE': {
//$Grequest->SendProcessOrder($data[$root]['google-order-number']['VALUE']);
//$Grequest->SendChargeOrder($data[$root]['google-order-number']['VALUE'],'');
break;
}
case 'CHARGING': {
break;
}
case 'CHARGED': {
break;
}
case 'PAYMENT_DECLINED': {
break;
}
case 'CANCELLED': {
break;
}
case 'CANCELLED_BY_GOOGLE': {
//$Grequest->SendBuyerMessage($data[$root]['google-order-number']['VALUE'],
// "Sorry, your order is cancelled by Google", true);
break;
}
default:
break;
}
switch($new_fulfillment_order) {
case 'NEW': {
break;
}
case 'PROCESSING': {
break;
}
case 'DELIVERED': {
break;
}
case 'WILL_NOT_DELIVER': {
break;
}
default:
break;
}
break;
}
case "charge-amount-notification": {
//$Grequest->SendDeliverOrder($data[$root]['google-order-number']['VALUE'],
// <carrier>, <tracking-number>, <send-email>);
//$Grequest->SendArchiveOrder($data[$root]['google-order-number']['VALUE'] );
$Gresponse->SendAck();
break;
}
case "chargeback-amount-notification": {
$Gresponse->SendAck();
break;
}
case "refund-amount-notification": {
$Gresponse->SendAck();
break;
}
case "risk-information-notification": {
$Gresponse->SendAck();
break;
}
default:
$Gresponse->SendBadRequestStatus("Invalid or not supported Message");
break;
}
I guess that case 'CHARGED' is the one, am I right?
Second question, do I need an SSL certificate to receive response from Google Checkout? According to this I do: groups.google.com/group/google-checkout-api-php/browse_thread/thread/10ce55177281c2b0
But I don's see it mentioned anywhere in the official documentation.
Thank you.
I integrated this into my site over 6 months ago. It's very low volume, but works good so far.
The first thing that you should worry about is 'CHARGEABLE'. This means that the credit card has been approved for the transaction, but it will not actually charge the funds until you take action. In order to send the charge request, simply un-comment the two lines under CHARGEABLE. You can change your settings to make it automatically charge the card in 'settings' > 'preferences', but you might as well just un-comment the 2 lines and leave your options open.
Note that you might want to WAIT for the 'risk-information-notification' and determine if the risk check passed before approving the charge ($data[$root]['risk-information']['eligible-for-protection']['VALUE']). Although, seems you are talking about digital goods the possibility of chargebacks might not matter to you.
At some point, I'm sure you should also check that the request has sufficient information for you to link the funds to some account before you charge it, but maybe this is just my paranoia.
The other state that I use is 'charge-amount-notification'. It's completely possible that there is a way to use 'CHARGED', but I don't that 'CHARGED' provides an amount that was actually charged. ($amount_charged = $data[$root]['total-charge-amount']['VALUE'];)
As for the SSL, if you check the location where you enter the callback URL it states the following:
"Specify a URL for Google to notify you of new orders and changes in order state. You must provide the URL of a server running 128-bit SSLv3 or TLS"
Answer to your comment:
I do this under 'new_order_notification', not sure if you can do it elsewhere.
$items = get_arr_result( $data[$root]['shopping-cart']['items']['item'] );
foreach( $items as $item ) {
if( !isset ( $item['merchant-item-id']['VALUE'] ) ) {
//error
return;
}
$request_item_id = $item['merchant-item-id']['VALUE'];
//save your item id with corresponding google order id for further processing
}
Yes, "Chargeable" is the first thing you need to look at in a Google Checkout order. When you click "Chargeable", a window will pop up for you to actually charge the order BUT be sure that the "Eligible for Protection" is True before actually charging the order. This ensure you that the payment is covered by Google payment guarantee. You can actually see it in the "Buyer Credit Verification" section in Google Checkout.

Categories