I'm trying to create a Google Places URL that can be reused and concatenated with a response from my database.. Not getting this to work and have been trying for a couple of days with no luck! If I echo out the both strings, from PHP on to my web page and copy&paste it, both addresses generate the same Google Places result, but when I print the JSON decoded response I get UNKNOW_ERROR from Google..
This is what I have been trying to use. The first and the second $googlePlacesAPI contains the exact same URL, just that one is concatenated and the other is "hard coded".
$googlePlacesAPI = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" .
$BarName. "+" . $BarCity . "&sensor=false&types=bar|night_club&key=" . $mySuperSecretKey;
$googlePlacesAPI = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" .
$BarName. "+" ."Göteborg". "&sensor=false&types=bar|night_club&key=" . $mySuperSecretKey;
To get the value of $BarCity I use this piece of code (before creating the $googlePlacesAPI variable):
$row = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM City WHERE ID = $CityID"));
mysqli_close($con);
$BarCity = $row['CityName'];
EDIT:
This is how I decode the answer:
$placesSearch = json_decode(file_get_contents($googlePlacesAPI));
You probably want to close the connection after you're done with $row:
$row = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM City WHERE ID = $CityID"));
$BarCity = $row['CityName'];
mysqli_close($con);
See a sample of mysqli_fetch_array usage at http://nl3.php.net/mysqli_fetch_array#example-1728
Related
i need your help to choose the fastest method to implement autocomplete on a search box in a web form.
i have to inputs to implement that, #city input and #street input.
the autocomplete of the street input must be filtered by the city input, we have 116K rows of street of the whole country.
how do i get it done right and smart?
thanks a lot!
The search.php file is called by the autocomplete() method of Autocomplete plugin. This file retrieves the skills data based on the search term and returns data as a JSON encoded array using PHP and MySQL.
The autocomplete() method make a GET request to source URL and added a query string with a term field. So, you can get the search term using PHP GET method. The following PHP code, fetch the records from the MySQL database (skills table) and filter the records by $_GET['term']. The filtered skill data returned to autocomplete() method as a JSON encoded array.
connect_error) {
die("Connection failed: " . $db->connect_error);
}
// Get search term
$searchTerm = $_GET['term'];
// Fetch matched data from the database
$query = $db->query("SELECT * FROM skills WHERE skill LIKE '%".$searchTerm."%' AND status = 1 ORDER BY skill ASC");
// Generate array with skills data
$skillData = array();
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$data['id'] = $row['id'];
$data['value'] = $row['skill'];
array_push($skillData, $data);
}
}
// Return results as json encoded array
echo json_encode($skillData);
?>
i am trying in pull my data from mySQL and convert it to a format I can then pass to google.maps API. I am thinking mySQL -> php -> javascript -> google.maps makes the most sense but am deffinitly open to other suggestions.
So far I have connected to and successfully queried my data into an array
<?php
//library of mysql functions including linkDB()
include('../sqlFunctions/sqlFunctions.php');
//Establish connection to database
if($link = linkDB()){
echo "connected to DB";
}
//set up a MySQL query. I am simply pulling geocoordinate ints, strings and boolean.
$sql = "SELECT title
,lat
,lng
,titleYou
,descriptionAre
,privacyRockstar
FROM shelters;";
if($results = $link->query($sql)){
echo "<p>Query succsessful.</p>";
}else{
echo "Query Failed";
}
//initialize an array to store data
$rows = array();
while ($data = $results->fetch_assoc()) {
$rows[] = $data;
echo "<br><br>Loop rotation: ";
var_dump($data);
}
echo "<br><p>The End of The Loop<p><br>";
var_dump($rows);
?>
Now I just need to convert this data into something usable I can pass to google.maps.
Before I was pulling JSON from a text file, which worked, but I want to flexibility and stability of a database. It was easy to parse into and array of Javascript Objects. Then I could just call the index and the property that I needed as you can see from this function I was using.
function setMarkers(){
for(i=0; i < jsonParsed.arrayOfObjs.length; i++){
//setting parameters to hand to google
var markerOptions = {
position : jsonParsed.arrayOfObjs[i].position,
map : mapCanvas,
description : jsonParsed.arrayOfObjs[i].title,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
};
//create marker
this ['marker' + i] = new google.maps.Marker(markerOptions);
}
}
Thank you for any light you can help shed on my issue.
It sounds like you already found your answer but I'll post for completeness.
Simply change your the var_dump($rows) line to json_encode($rows).
Read more about json_encode in the php docs.
You probably want to have two php files:
api.php file that emits Content-type: application/json
index.php file that emits Content-type: text/html and calls api.php
On the index page, you can make an AJAX call to your API endpoint and then use JSON.parse(response).
I just realized that I cannot call directly on a URL from my AngularJS application due to CORS. Therefore, I expect I will have to use the Javascript API.
The following link provides me with the data I want:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + myPosition.lat + ',' + myPosition.lng + '&rankby=distance&key=' + key + '&sensor=false&type=clothing_store
However, I cannot figure how to achieve the same using the Javascript API. I found this in the documentation, but I do not need a map - just the names and coordinates of the nearby stores.
How can I get a hold of the same data using the Javascript API?
If you've already got a Google Maps for JS API Map Key, you can do a Places query from the server side. Note, however, that you're limited to 1000 queries per day.
You can probably do this directly in your client and avoid CORS issues, but here's how I've done it previously using PHP:
<?php
function ReturnEmpty()
{
// Something's wrong, return an empty set.
echo '{"d":[]}';
}
$q = (isset($_GET["query"])) ? $_GET["query"] : 'NULL';
if( $q == "" )
{
ReturnEmpty();
}
else
{
// I'm showing the "textsearch" option, but there is also a "nearbysearch" option..
$url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query="
. urlencode($q)
. "&key=YOUR_GOOGLE_MAPS_KEY_HERE";
$json = file_get_contents($url);
$data = json_decode($json, true);
echo $data;
}
?>
You can use the nearbySearch(request, callback) method on google.maps.places.PlacesService(map).
In your case, the request should have a location (that contains the lat and lng) and a radius.
There are code samples here.
I want to dynamically create webpages using a php script(for example : category.php) which takes on variable 'category' and do a mysql query to get data from the server and create a webpage.
category.php
< ? php
include_once("php_includes/db_conx.php");
$sql = "SELECT * FROM PRODUCTS WHERE CATEGORY = 'CLOTHING' ";
$result = $db_conx->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
/*GENERATE SOME WEBPAGE*/
}
}
? >
So when a user clicks a link "/category/clothing " it should pick the variable value (category = 'clothing' ) from this link and dynamically generate a webpage with the address "www.example.com/category/clothing" instead of something like "www.example.com/category/?category=clothing"
What i want to avoid is a url having '?' and '='
So I want to achieve 2 things:
A single php file generating pages dynamically by taking values from links like "/category/clothing"
Url of the new webpage should be simple and proper "www.example.com/category/clothing" (of course it should be same as the link clicked ) and not like "www.example.com/category/?category=clothing"
Can someone write a example php or js script which can achieve this or point me in the right direction(in case its very simple)
PHP can't do this by itself. You are going to need an .htaccess apache module called mod rewrite. Here is a tutorial how to make pretty urls.
http://code.tutsplus.com/tutorials/using-htaccess-files-for-pretty-urls--net-6049
There seem to be many questions in around this topic but none seem to answer my question. I have a simple website with a signup form, and when users enter their email I want to push this as a new row in a Google Spreadsheet I have already setup. I don't want the user to authenticate or even know about this spreadsheet. How do I authenticate so I can start using the Google API? Code/pseudocode would be greatly appreciated! Here are some examples that do not answer my question:
Using Google Spreadsheet as DB for apps
Google spreadsheet as db for web applications
Here's a link to a library for accessing Google Spreadsheets:
https://github.com/EastCloud/node-spreadsheets
Note: Ive not actually used this lib
You will need to use PHP and the Zend GData Library.
When you post your form to your PHP script, you'll need to collect all of the variables into an associative array that you then pass to the insertRow method of Zend_Gdata_Spreadsheets.
It's important to note that your spreadsheet must contain column headers for my example to work. E.g. First Name / Last Name and it's important to note that when you target these column headers in a script, they will need to be all lowercase and stripped of spaces because this is how the spreadsheet expects them.
Here is a basic example of the PHP script:
<?php
$errors = array(); // use this to create an associative array to json encode and send back any errors
$rowData = array(); // this will be the associative array that gets passed to the insertRow method
$firstName = $_POST['firstName'];
if(isset($firstName)){
$rowData['firstname'] = $firstName; // note the key 'firstname' must equal the column header in your spreadsheet which you are inserting the value into. the column header name key should be all lowercase and not contain spaces regardless of if you have it in the spreadsheet
}else{
$errors['firstname'] = '1';
}
$lastName = $_POST['lastName'];
if(isset($lastName)){
$rowData['lastname'] = $lastName; // note the key 'lastname' must equal the column header in your spreadsheet which you are inserting the value into. the column header name key should be all lowercase and not contain spaces regardless of if you have it in the spreadsheet
}else{
$errors['lastname'] = '1';
}
set_include_path($_SERVER['DOCUMENT_ROOT'] . '/library/');
$spreadsheetKey = 'your-spreadsheet-key';
$worksheetId = 'your-worksheet-id'; // if you only have one worksheet this will be 'od6'
require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);
$user = "your-user-name-at-gmail-dot-com";
$pass = "your-password";
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$spreadsheetService = new Zend_Gdata_Spreadsheets($client);
$query = new Zend_Gdata_Spreadsheets_DocumentQuery();
$query->setSpreadsheetKey($spreadsheetKey);
$feed = $spreadsheetService->getWorksheetFeed($query);
global $spreadsheetService,$spreadsheetKey,$worksheetId,$rowData;
$insertedListEntry=$spreadsheetService->insertRow($rowData,$spreadsheetKey,$worksheetId);
$returnObject['success'] = 'true';
echo(json_encode($returnObject));
?>
Let me know if this works for you.