I'm Trying to get the Latitude & Longitude from Google maps Places Searchbox.
you can find the whole code here.
I don't have a deep knowledge to Javascript so I've seen a couple of solutions that doesn't actually work and I think I might misplace the code that gets the lat and lng!
So please help me to figure out where should I actually put the solution.
I've tried
place.geometry.location.lat()
place.geometry.location.lng()
it somehow doesn't work!
I'd like to send these lat and lng to HTML element
so I can send them as form to a PHP action Page and then to mysql Database..
Is there a shortcut that help me send them directly to the mysql DB or to PHP directly?
Without the rest of your code, I can only show you what I have done using a form to collect an address. Using php 7 with json_decode(). There is a more efficient way to do this, but it works for me. Hope this helps.
//create string holding address to run through google geolocation API for Lat/Long
//make sure to clean your posts, I use functions from another page that cleans htmls tags, trims and removes slashes and/or runs through a reg ex to replace and/or remove unwanted entries for the particular fields type.
$address = clean_post($_POST['cust_street']).' '.clean_post($_POST['cust_city']).' '.clean_post($_POST['cust_state']).', '.clean_post($_POST['cust_zip']);
// Get JSON results from this request
$url = 'https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false&key='.APIKEY;
$geo = file_get_contents($url);
// Convert the JSON to an array
$geo = json_decode($geo, true);
if ($geo['status'] == 'OK') {
// Get Lat & Long
$latitude = $geo['results'][0]['geometry']['location']['lat'];
$longitude = $geo['results'][0]['geometry']['location']['lng'];
}else{
$latitude = NULL;
$longitude = NULL;
$sessData['status']['type'] = 'alert alert-warning';
$sessData['status']['msg'] = 'Sorry, but it seems the address you entered is not being recognized by Google Maps API service.';
//die or exit, do something on failure
}
Then you can add these variables to your DB insert/update and/or echo them out as needed. This very code is run through an applet I am working on that takes a given address entered into a customer form and then processes that address, gets Lat and Long and then upon success, places that into the array I am running through the insert into my DB. I can then call on that to locate that customers lat and long on a map at a later date.
$custData = array(
'users_id' => $usr_id,
'cust_first_name' => clean_post( $cust_first_name ),
'cust_last_name' => clean_post( $cust_last_name ),
'cust_email' => clean_email( $cust_email ),
'cust_street' => clean_post( $cust_street ),
'cust_city' => clean_post( $cust_city ),
'cust_state' => clean_post( $cust_state ),
'cust_zip' => clean_post( $cust_zip ),
'cust_phone1' => clean_phone( $cust_phone2 ),
'cust_lat' => clean_phone( $latitude ),
'cust_long' => clean_float( $longitude ),
//etc,etc,etc
);
//$cust = new User(); further up in page
//insertCust() function comes from user class stored in class.user.php
$insert = $cust->insertCust($custData);
//set status based on data insert
if($insert){
//set some session variables and store them before any header redirects.
$_SESSION['status']['type'] = 'alert alert-success';
$_SESSION['status']['msg'] = 'You have registered '.$custName.' successfully!';
}
Btw, I am currently going through this document on XSS security and have found it to be most helpful: XSS_Filter_Evasion_Cheat_Sheet
Hope this helps.
Related
So I have the following JSON:
[{"username":"User1","password":"Password"},
{"username":"User5","password":"passWord"},]
Generated from:
<?php $username = $_POST["username"]; ?><br>
<?php $password = $_POST["password"]; ?><br>
<?php
$currentData = file_get_contents('UserJSON.txt');
$array_data = json_decode($currentData, true);
$extra = array(
'username' => $username,
'password' => $password
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('UserJSON.txt',$final_data)) {
print("working");
}
?>
After the user logs in they have the ability to make a post, how would I go about creating a post array for each user and how would I add to it dynamically ?
This is all I have and I have tried many different ways, but cant seem to figure out how to make it dynamic.
<?php
$urlText = $_REQUEST["urlText"];
$currentData = file_get_contents('UserJSON.txt');
$array_data = json_decode($currentData, true);
//for loop
$array_data[i]['Posts'] = $urlText;
//end for loop
$final_data = json_encode($array_data);
if(file_put_contents('UserJSON.txt',$final_data)) {
}
?>
In this situation though, posts is not an array, it just simply overwrites what already there.
[{"username":"User1","password":"Password","Posts:{"This is a post"}},
{"username":"User5","password":"passWord"},"Posts:{"This is a post2"}}]
Therefore, how do I add a posts array and how do I add to it dynamically ? I have not been able to figure such a simple thing out for a very long time
File get contents from like "posts/useridhere.txt", or allposts.txt
You will also need to use unique post IDs.
Json decode your posts JSON
Add post content to array
Json encode array
Write new json to the users post file
Ultimately I do not recommend this. If you want a paid internship I'll teach you how to use MySQL. We make websites :) but if you want to do it this way, you'll need a JSON file to store unique post IDs or even store all posts in one file. The problem is that you'll have a limit of how many posts can be stored in that single JSON array. I hope this answer is enough to help you. It's all the steps needed
$posts = file_get_contents($postsFile);
$posts = json_decode($posts);
$newPost = array(
"user"=>$user,
"postTitle"=>$string,
"text"=>$content
);
$posts[] = $newPost;
$newPostID = count($posts); // will not work properly (for linking posts) once you delete a post - you need unique post ids generated!
$posts = json_encode($posts);
// Overwrite your posts file with $posts. It will have all posts you need :)
Currently,I have created a page showing all the locations of the users (all from MySQL database) on google map. But because there are 5000+ user locations, it takes a long time to load the page.
I would like to make it more efficiently by only querying the user locations within certain area. (the area I am viewing)
What could I do to make it more efficient? Does google maps API support the feature that I want? I heard I can do geofencing mysql, but I cannot really find how to use it.
Thank you in advance.
There are probably many ways to do what you want. If you have the longitude and latitude of the users (which sounds like you do) then instead of loading all user locations (select latitude, longitude from users) then narrow down the location by specifying a range for the coordinates of your user, so your select looks something like this (in pseudo query)
select latitude, longitude from users where latitude between (user.latitude + whateverrangeyouwant and user.latitude - whateverrangeyouwant) AND longitude between (user.longitude + whateverrangeyouwant AND user.longitude - whateverrangeyouwant);
The range can probably be taken from the map.bounds property
You can then send this back to your script using a service that will then remove the markers from the map and add the one ones based on your service response. So your javascript would look something like this (in pseudo code)
get user location;
send service request for user locations and get them back in an array
remove current markers
add new markers from service result
The service in PHP probably look something like this:
$minLat = $_REQUEST['lat'] - ($_REQUEST['dl'] / 2);
$maxLat = $_REQUEST['lat'] + ($_REQUEST['dl'] / 2);
$minLon = $_REQUEST['lon'] - $_REQUEST['dln'];
$maxLon = $_REQUEST['lon'] + $_REQUEST['dln'];
$query = 'SELECT locations.latitude,
locations.longitude
FROM locations
WHERE (latitude BETWEEN ' . $minLat . ' AND ' . $maxLat . ') AND
(longitude BETWEEN ' . $minLon . ' AND ' . $maxLon. ')';
}
$query = DB::query($query);
$json = array();
while($location = $query->fetch_assoc()) {
$json[] = $location;
}
header('Content-Type: application/json');
echo json_encode($json);
exit();
Hope that helps.
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'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
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.