Google Places - Get formatted address without user input - javascript

I have been sifting through documentation unsuccessfully and need help. I need to access the first value in Google places autocomplete or geocode the lat lng coords I have in Google Places. I am auto populating the field with say "Palo Alto" and need Google Places' first suggestion for an auto complete of that city. I have tried using the Google Geocode feature but the results are different than the Places API and therefore useless to me. Example places outputs Palo Alto, CA and the geocode feature outputs Palo Alto, CA USA. I have tried hacking it together by reverse geocoding the lat lng splitting the string above to only say Palo Alto and populating an input field that is hooked into a Places autocomplete, but I can't get it to trigger. I have a script written to pull the output from the autocomplete results; I just need to trigger it. I have tried using $('myCity').trigger('keypress'); once I have inserted Palo Alto into the input field to no avail. All suggestions on what steps to take next are welcome. I have also looked into the following code, but I want to do it without the map and i get a javascript error when i remove it. "TypeError: a is undefined [Break On This Error] (66 out of range 46)"
var lat = -130;
var lng = 37;
var request = {
location: new google.maps.LatLng(lat, lng);
};
var service = new google.maps.places.PlacesService(map);
service.search(request, function (results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
console.log(results[i])
}
}
});
Thanks for your help.

You need to perform a Text Search.
Go to Places Library and go down to Text Search Requests.
Heres an example:
var map;
var service;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '500',
query: 'restaurant'
};
service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
Note: In your case change the request to this:
var request = {
query: 'Palo Alto'
};

Related

How to Get JSON Results from Google Places JS Library using textsearch()?

Question: How can I get the ~same JSON response that I get when I call Google Places server-side API /textsearch/ in my browser, but using Google Places JS Library instead?
Here is the server-side Google Places API /textsearch/
https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurants+pyrmont&key=AIzaSyAXPJDWXhzlAY0N8mMUcgFJ6yNSEd0vMg8
Here is the sample code:
I've tried to console.log() the JSON, but I can't get any JSON to log to the console.
var map;
var service;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '500',
query: 'restaurant'
};
service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
console.log(place.id)
}
}
Here's the documentation in case it's helpful: https://developers.google.com/maps/documentation/javascript/places#TextSearchRequests
Thank you for any help you can provide!

Google Maps API and JavaScript Issues :-(

Ive been working on a Google Maps application and have hit a hurdle due to a lack of knowledge in js me thinks?!
So... here's my JSON object
{"pickuppoint0":"LE9 8GB","pickuppoint1":"LE2 0QA","pickuppoint2":"LE3 6AF","pickuppoint3":"LE2 8GB","pickuppoint4":"LE8 8TE","pickuppoint5":"LE2 2GB","pickuppoint6":"LE1 6AF"}
And here's a loop through the JSON object...
$.each(alltravelgroups, function(k, v){
for(var i=0; i < boxes.length; i++){
var bounds = boxes[i];
if(bounds.contains(getLatLng(v))){
alert("im here");
}
}
});
And here's my getLatLng() method I've created...
function getLatLng(pickuppoint) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': pickuppoint}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
return results[0].geometry.location
} else {
alert('getLatLng Geocode was not successful for the following reason: ' + status);
}
});
}
Now... what I'm trying to do is simply take the value from each key/value pair and produce a LatLng object that can then be used within the "bounds.contains()" method for searching within the bounds box provided by the RouteBoxer class.
The problem I'm facing is the value returned by the getLatLng method is "undefined" when using alert(getLatLng(v)) and should just be a 'location' containing both latitude and longitde? Anyone able to point what I'm doing wrong?
Please refer the link below.
http://jsfiddle.net/y829C/13/
var mapOptions = {
center: new google.maps.LatLng(-33.8665433, 151.1956316),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
In the above code, semicolon is missing in return results[0].geometry.location.

better approach then setTimeout on Google Map V3

in my Asp.net Web Application where i am using the setTimeout to Get rid of
geocoder OVER_QUERY_LIMIT, the shorter time out is 10ms which is too longer for me, I have 800 above addresses coming from SQL SERVER which would be increased because of this setTimeout will take about 5 to 7 mints to take places of all the markers on map and that`s frustrating. I researched and saw this link setTimeout: how to get the shortest delay
but cant figure out what he want to do actually. please someone guide me....
function InitializeMap() {
// Here am calling the webService by PageMethods in which CityNames, Countries Name will take their places
PageMethods.GetCitiesbyUser_Extender(onSucess);
var myOptions =
{
zoom: 0,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
// Creating latlngbound to bound the markers on map
var bounds = new google.maps.LatLngBounds();
//// Creating an array that will contain the addresses
var places = [];
// Creating a variable that will hold the InfoWindow object
var infowindow;
// create this to add the marker Cluster on map
mc = new MarkerClusterer(map);
var popup_content = [];
var geocoder = new google.maps.Geocoder();
// image for ballon i want to change default ballon to this
var iconimage = "http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,008CFF,000000&ext=.png";
var markers = [];
// Create this function for passing the values which was taken by webservice cntName is the return in webservice
function onSucess(cntName){
// loop through the cntName to pass the individual City one by one from geocode
for (i = 0; i < cntName.length; ++i) {
//for fixing the issue use closure to localize the cntName[i] variable before passing into geocode and callback function within it.
(function CreateMarkAndInfo(address) {
geocoder.geocode({ 'address': address },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
places[i] = results[0].geometry.location;
var marker = new google.maps.Marker({
position: places[i],
title: results[0].formatted_address,
map: map,
icon: iconimage
});
markers.push(marker);
mc.addMarker(marker);
google.maps.event.addListener(marker, 'click', function () {
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
// Setting the content of the InfoWindow afterward
infowindow.setContent(popup_content[i]);
// Tying the InfoWindow to the marker afterward
infowindow.open(map, marker);
});
// Extending the bounds object with each LatLng
bounds.extend(places[i]);
// Adjusting the map to new bounding box
map.fitBounds(bounds);
// Zoom out after fitBound
var listener = google.maps.event.addListenerOnce(map, "idle", function () {
if (map.getZoom() < 10) map.setZoom(2);
});
}
else {
// if geocode will end the limit then make delay by timer in order to avoid the OVER_QUERY_LIMIT
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function () { CreateMarkAndInfo(address); }, (15)); // here i think i should use better approch but for now it`s ok.
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
}
});
})(cntName[i]);// End closure trick
}
}
}
google.maps.event.addDomListener(window, 'load', InitializeMap);
Edit:
#just.another.programmer i cant because there is no latitute and longitude in DB, client will add cities and countries by him self thats why i had to convet city and country names by geocode and geocode doing it`s job accuretly here
How i am calling the City and country Names by web service
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod()]
public static string[] GetCitiesbyUser_Extender()
{
System.Data.DataSet dtst = new System.Data.DataSet();
string ses = HttpContext.Current.Session["UserName"].ToString();
USTER.Dal.clsSearch clssearch = new USTER.Dal.clsSearch();
// Assinging the Stroed Procedure Method to DataSet
dtst = clssearch.GetAllCitiesByUser(ses);
string[] cntName = new string[dtst.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (System.Data.DataRow rdr in dtst.Tables[0].Rows)
{
// Columns Name in SQL Server Table "CityName" and "CountryName"
cntName.SetValue(rdr["CityName"].ToString() +","+ rdr["CountryName"].ToString() , i);
i++;
}
}
catch { }
finally
{
}
return cntName;
}
Geocode your addresses one time when you first get them, then store the lat/long in your db so you don't have to geocode again. This will dramatically reduce your geocode requests and remove the need for setTimeout.

Place search request giving inconsistent results using bounds

As per this link: http://code.google.com/apis/maps/documentation/javascript/places.html#place_search_requests
The method can take either
-a point and a radius or
-a rectangle boundary
using the point + radius gives me correct results, however the max radius is only 50 km and I need my search to be up to 1000 km, so I tried using bounds.
When my bounds are small I get the same correct results as the point + radius, however when I increase the bounds I get no results at all.
The code below will give correct results, however if you replace the var sw and var ne with the commented out coordinates, it no longer works.
ie. kitchener is found within the boundary between ayr and guelph, but not in the boundary between detroit and ottawa. Which doesn't make any sense if you look at the map.
<script type="text/javascript">
var map;
var infowindow;
function initialize() {
var Cambridge = new google.maps.LatLng(43.346528, -80.417962);
var sw = new google.maps.LatLng(43.292501,-80.543175); // 41.914541,-83.282318
var ne = new google.maps.LatLng(43.605057,-80.156250); // 45.580391,-76.283051
var zoneBounds = new google.maps.LatLngBounds(sw,ne);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: Cambridge,
zoom: 10
});
var request = {
bounds: zoneBounds,
//location: Cambridge, //using location and
//radius: 500000, //radius works
name: ['Kitchener, ON']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I'm supposed to be able to use PlacesServiceStatus to find the status of the request, i assume this would give me insight into the problem but I have no idea how to retrieve the status codes
Any help with this would be much appreciated
Thanks!
edit: ok, I added alert(status); and the status says it's "ZERO_RESULTS"
In the callback method you could do something like
function callback(results, status) {
window.alert(results.length);
that will tell you how many results you have, you could loop round them something like this...
for (var i = 0; i < results.length; i++) {
window.alert(results[i].formatted_address);
}
I've tried this myself and yes, if the bounds are greater than 50km then the results are pretty useless. I could guess at an answer; if the bounds are very large then it may involve too much of a hit on the Google servers. However, I don't like that answer so if someone knows better; help us out!
Another alternative is to use the Places Autocomplete -
https://developers.google.com/maps/documentation/javascript/places#places_autocomplete
You could use the geolocation but I doubt that will provide the responses you're looking for, for example if you geocode 'enfield' it will show you all the enfields in the world, if you geocode 'enf' it will show you a finish airport!

fetch the list of location with a particular location as center and radius (say 50km) , using google location API

I need the list of locations (areas/subareas) in a particular city.
I thought, google api might be a possible option to fetch this. if i pass city's lat/long and radius then there must be some way to fetch the list of locations.
however i could not find any possible solution?
Can any one help me out?
Yeah, Google Maps JavaScript API V3 can be a good solution for it. If you check this website, there is a similar example of it:
var map;
var service;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '500',
types: ['store']
};
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
There it finds stores in a specific radius from Pyrmont. You can take a look at it documentation, change the type parameter (see this list) for whatever you want and get its result in that callback function. After that, you could use those cities' info for your purpose.

Categories