Create Gmap Link from an address - google-maps

Given a street, city, lat/long, and zip, how do you create an anchor link to a Google Map?
Following a Gmap result, I tried to mimic the link it gave. So far, I have tried:
$street = str_replace(' ', '+', $location['street']);
$street = str_replace('#', '%23', $street);
$city = str_replace(' ', '+', $location['city']);
$state = str_replace(' ', '+', $location['state']);
$zip = $location['zip'];
$lat = $location['lat'];
$long = $location['long'];
$map = 'http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q='.$street.'+'.$city.'+'.$state.'&sll='.$lat.','.$long.'&ie=UTF8&hq=&hnear='.$street.',+'.$city.',+'.$state.',+'.$zip.'&ll='.$lat.','.$long;
Sometimes it works, other times I get "We could not understand your request". Does anyone know of a way to make this work for any result?

I've always simplified it down to just the query (q) and i've never had an issue
http://www.google.com/maps?q=address(tooltip/infowindow title)
whatever you put in the () will be the tooltip text and the title for the infowindow

Related

Laravel: Querying based on Input. If input is empty, get all

I have a calendar (FullCalendar) where the user can filter down results based on a few params (Tutor Secondary Tutor, Lesson, Location). When the user makes a change to the query it hits the following code.
The issue I am having is the 'OR'. What I really want is an IF input is null then get all.
If User { Get all lessons where lead_tutor_id = 1 and secondary_tutors_id = 1 }
If User and Location { Get lessons where the user is as above, but have location_id = 3 }
etc, etc.
So, is there a way I can fall back to get ALL the results IF only one or two filters are set?
$current_events = Calendar::Where(function($query) use ($start_time, $end_time, $tutor, $location, $lesson)
{
$query->whereBetween('date_from', [$start_time, $end_time])->orderBy('date_from')
->whereRaw('lead_tutor_id = ?
OR secondary_tutors_id = ?
OR location_id = ?
OR lesson_id = ?',
[
$tutor, // Input get() for user
$tutor, // Input get() for user
$location, // Input get() for location
$lesson, // Input get() for lesson
]
);
})->with('lessons', 'leadtutor', 'secondarytutor')->get();
I've been playing with Query Scopes, but this seems to fail if passing a NULL value through to it.
Any help is very much appreciated. Thanks in advance.
You can build the query on forehand, store it in a variable and use it once its build.
$query = isset($var) ? $var : '';
$query .= isset($othervar) ? $othervar : '';
whereBetween(*)->orderBy(*)->whereRaw($query)
Only thing you need to keep in mind is to insert the 'OR's in the right place . So have like a check for wether it is the first thing to be inserted or not, if not then put 'OR' in front of it.
Hope that is enough info to help you.
After the advice from Saint Genius, I have got this working:
$built_query = [];
isset($lead_tutor) ? $built_query['lead_tutor'] = 'lead_tutor_id = ' . $lead_tutor . ' ' : null;
isset($secondary_tutor) ? $built_query['secondary_tutor'] = 'secondary_tutors_id = ' . $secondary_tutor . ' ' : null;
isset($location_id) ? $built_query['location'] = 'location_id = ' . $location_id : null;
isset($lesson_id) ? $built_query['lesson'] = 'lesson_id = ' . $lesson_id : null;
// Flatten the array so we can create a query and add the word ADD in between each element.
$built_query = implode(" AND ", $built_query);
// Run the query
$current_events = Calendar::whereBetween('date_from', [$start_time, $end_time])->orderBy('date_from')->whereRaw($built_query)->with('lessons', 'leadtutor', 'secondarytutor')->get();

Get polygons within polygons in Google maps

With the help of #Dr.Molle answer I learnt to do free hand drawing in Google maps. Now I'm trying to get the polygon drawn within a polygon something like in the below SS
I want to get the polygons marked in yellow and green within the black.
I'm not sure whether this is possible or not. Please shed some light on this issue.
Updates: on further research I learnt about a method called containsLocation(point, polygons) which is used to find whether the given lat/lng point is within the polygon or not.
But sadly there is no default method to check polygons within polygon provided by Google maps :(
You can check if a polygon is within another polygon by looping through each point of the inner polygon and testing if it is contained within the outer polygon using containsLocation().
var isPolygonInsidePolygon = function (innerPolygon, outerPolygon) {
var pointsInside = 0;
var pointsOutside = 0;
innerPolygon.getPath().getArray().map(function (x) {
(google.maps.geometry.poly.containsLocation(x, outerPolygon)) ? pointsInside++ : pointsOutside++;
});
return (pointsOutside > 0) ? false : true;
};
The JavaScript map() function may not work in older browsers, IE8 or lower.
This is a GIS question. Google Maps API isn't really a full-blown GIS. If you want an open-source solution, I suggest loading your yellow and green polygons into a PostGIS database. Then you can query the database.
As an example, you can encode the drawn polygon as a POLYGON object which has the format:
POLYGON((lon lat, lon lat, lon lat, lon lat, ... lon lat))
And then send that to a PHP file from javascript like (you'll wrap this in a $.get() command or similar and return json results:
getParcels.php?bounds=POLYGON((lon lat, lon lat, lon lat, lon lat, ... lon lat))
In the PHP file, query the PostGIS database and return the ids of the yellow and green polygons:
<?php
$pgcon = pg_connect ("dbname=gis user=gisuser connect_timeout=5") or die ( 'Can not connect to PG server' );
if (!$pgcon) {
echo "No connection to GIS database.\n";
}
$bounds = urldecode($_GET["bounds"];
$ewkt = 'SRID=4326;' . $bounds);
$json = ''; // this will contain your output
// Here I am returning the polygon geometry and the parcelID...
$query .= <<<EOD
SELECT
ST_AsGeoJSON(the_geom) as geom,
parid
FROM
parcels
WHERE
ST_Intersects(the_geom, ST_GeomFromEWKT( $1 ));
EOD;
$result = pg_query_params($pgcon, $query, array($ewkt));
if($result) {
$json = '{"type":"FeatureCollection", "features":[';
while($row = pg_fetch_assoc($result)) {
$json .= '{"geometry":' . $row['geom'] . ',';
$json .= '"type":"Feature","properties":{"parid":"' . $row['parid'] . '"}},';
}
$json = substr($json, 0,-1).']}';
}
echo $json;
?>
This will return the parcels that intersect your polygon using the ST_Intersects command in PostGIS.
An alternative implementation working from #chris-smith solution that might be faster, since it doesn't keep looping if it finds an outside point:
function isPolygonInsidePolygon( innerPolygon, outerPolygon ) {
var points = innerPolygon.getPath().getArray();
for( var i = 0; i < points.length; i++ ){
if( ! google.maps.geometry.poly.containsLocation( points[i], outerPolygon) ){
return false;
}
}
return true;
}

Query two combined fields with one value

I have a table name 'user' for example. I have field 'name' and field 'family' in this table.
I use jQueryUI auto-complete for top search in my site for search people just like Facebook.
Example of jQueryUI I use (half code):
$( "#mainsearch" ).bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
And I have PHP files get search result code like this:
$name = $_GET['term'];
$results = array();
$s = qselectall("select * from user where(name LIKE '%$name%' or family LIKE '%$name%' ) limit 15",$db);
while($f = mysqli_fetch_array($s,MYSQLI_ASSOC)){
if($userid != $f['id']){
$name = $f['name'].' '.$f['family'];
$url = $siteurl.$f['username'].'/';
array_push($results, array('id' => $f['id'],'value' => $name,'url' => $url));
}
}
echo json_encode($results);
But it has 1 problem.
User's cannot search with name and family.
They must insert name OR family just in input box for it to work.
Is there any SQL code for search LIKE where( name and family = $text) ?
EXAMPLE:
We have someone with name 'alex' and with last name 'alexian'.
So user search for 'alex alexian' but they get no results why?
Because not name and not family in table = 'alex alexian'.
So they must search 'alex' or 'alexian' for it to work.
Try this:
SELECT * FROM user
WHERE concat_ws(' ',name,family)
LIKE '%$name%';
The concat_ws function concatenates multiple columns 'with separator' (_ws). In this case, the separator is a space (' '). See the MySQL documentation for further information.
Demo: http://www.sqlfiddle.com/#!2/aac0f/8

Google Geocoder API Output Format

I noticed that my google geocoding has been deprecated and has brought my website to its knees. I could really use someone's help figuring out this last piece of the puzzle. I had the old code that produced a single output "$Coords" that the rest of my website is dependent upon. Could you please help me figure out how to make the new api have the same output. Here was my old code:
$address = str_replace('#', '', $address);
$address = str_replace(' ', '+', $address);
$XMLUrl = 'http://maps.google.com/maps/geo?q='.$address.'&key='.$api.'&sensor=false&output=xml&oe=utf8';
$XMLUrl = 'http://maps.googleapis.com/maps/api/geocode/xml?address='.$address.'&sensor=false';
$XMLContents = file_get_contents($XMLUrl);
$XML = new SimpleXMLElement($XMLContents);
$Coords = explode(',',$XML->Response->Placemark->Point->coordinates);
return $Coords;
Here is what I have for the new code. I just can't figure out how to have it output as $Coords:
$address = str_replace('#', '', $address);
$address = str_replace(" ", "+", $address);
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region");
$json = json_decode($json);
$lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
The rest of the website depends upon the geocoding stored as $Coords and not as $lat or $long. I really really appreciate any help I can get.
I needed to save it as an array. Duh
$Coords = $long.', '.$lat;
$Coords = explode(',',$Coords);

Drupal 6 : Not able to fetch group_id(gid) from OG table

I am creating nodes pro-grammatically by fetching emails. Where I am splitting the subject of the mail for creating it for specific group & the title of the node.
Now I want to fetch the group_id by the description of the group and wrote query for it, but it's not working. Let me paste the code here..
list($group_name, $title_text) = explode(', ', $title);
$query = "SELECT * FROM {og} WHERE og_description = ' ".$group_name." ' ";
$group_details = db_query($query);
while ($group = db_fetch_object($group_details)) {
$gid = $group->nid;
}
echo $gid;
echo $gid is giving nothing. Though $group_name = 'Logo design' & gid = 1442 for it in table.
Is there anything I am missing here ?
Check out the following two pages , the examples give here does not use the single quotes around the placeholder in the query ($group_name - in your example) .
http://drupal.org/node/310072
One of the lines says "Note that placeholders should not be escaped or quoted regardless of their type" .
http://drupal.org/node/1407528
I have solved it. Here is the answer:-
$title = "ED's presentation, This content is for ed's presenation"; //This is the subject of the mail, which I am fetching.
list($group_name, $title_text) = explode(', ', $title);
$query = "SELECT nid FROM {og} WHERE og_description = '".$group_name."'";
$group_details = db_query($query);
while ($group = db_fetch_object($group_details)) {
{
$gid = $group->nid;
}
Thanks :)