Does anyone know why my "nearbySearch" google place search is missing data?
When I do a nearby search using the places API, every weekday_text array returns as empty but when I do a "getDetails" request to one of the locations in the initial search, the weekday_text is returned.
http://codepen.io/anon/pen/RGBVJR
var map;
var service;
// Nearby search
var showPosition = function() {
var geolocation = new google.maps.LatLng(51.5074, -0.1278);
map = new google.maps.Map(document.getElementById('map'), {
center: geolocation,
zoom: 15
});
var request = {
location: geolocation,
radius: '500',
types: ['bar']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
};
showPosition();
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log(results);
}
}
// Direct location check
function altTest() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(51.5074, -0.1278),
zoom: 15
});
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: 'ChIJ78fbAc8EdkgRWG1dhffz9AY'
}, function (place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(place.opening_hours.weekday_text);
}
});
}
altTest();
<div id="map">
</div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
Please see the console.logs to see the data discrepancy.
Any ideas why this is the case? I would rather not have to do a second API request to retrieve the weekday requests.
Thanks,
Tom
nearbySearch returns an array of PlaceResult objects.
As you can see here, PlaceResult doesn't have weekday_text property.
Related
I am trying to add google map api to my project I following an instruction on document but I am getting this error
b is not the function
enter image description here
I read a document on function nearbySearch() it take at least one parmater and another on can be callback or others i tried add them but still Im getting this error.
here is my code
var map;
var lat = 51.23916571;
var lng = -0.586997652;
function initMap() {
// Create the map.
var pyrmont = new google.maps.LatLng(lat, lng);
map = new google.maps.Map(document.getElementById("map"), {
center: pyrmont,
zoom: 17,
});
// Create the places service.
const service = new google.maps.places.PlacesService(map);
var request = {
location: pyrmont,
radius: '1000',
type: ['gym']
};
// Perform a nearby search.
service.nearbySearch(request)
console.log(service)
}
Did I write something wrong?
You are missing the required callback function.
See the example in the documentation.
Per the documentation:
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
This method takes a request with the following fields:
Either of:
++ bounds, which must be a google.maps.LatLngBounds object defining the rectangular search area; or
++ a location and a radius; the former takes a google.maps.LatLng object, and the latter takes a simple integer, representing the circle's radius in meters. The maximum allowed radius is 50 000 meters. Note that when rankBy is set to DISTANCE, you must specify a location but you cannot specify a radius or bounds.
<snip - removing optional parameters>
type — Restricts the results to places matching the specified type. Only one type may be specified (if more than one type is provided, all types following the first entry are ignored). See the list of supported types.
You must also pass a callback method to nearbySearch(), to handle the results object and google.maps.places.PlacesServiceStatus response.
Example from the documentation:
var request = {
location: pyrmont,
radius: '500',
type: ['restaurant']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
proof of concept fiddle
working code snippet (with your request):
var map;
var lat = 51.23916571;
var lng = -0.586997652;
var bounds;
var infowindow;
function initMap() {
// Create the map.
var pyrmont = new google.maps.LatLng(lat, lng);
map = new google.maps.Map(document.getElementById("map"), {
center: pyrmont,
zoom: 17,
});
bounds = new google.maps.LatLngBounds();
infowindow = new google.maps.InfoWindow();
// Create the places service.
const service = new google.maps.places.PlacesService(map);
var request = {
location: pyrmont,
radius: '1000',
type: ['gym']
};
// Perform a nearby search.
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log("results.length=" + results.length);
for (var i = 0; i < results.length; i++) {
var marker = createMarker(results[i]);
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
// display the place "name" and "place_id" in the infowindow.
infowindow.setContent(place.name + "<br>" + place.place_id);
infowindow.open(map, this);
});
return marker;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
flex-basis: 0;
flex-grow: 4;
height: 100%;
}
<!DOCTYPE html>
<html>
<head>
<title>Place Search Pagination</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=places&v=weekly&channel=2" async></script>
</body>
</html>
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!
fairly new to javascript and trying to make a simple map application. I am trying to center a new map around an address that is passed through a function. The issue I have is it is always being returned null which I do not understand, do I have to specify return types in the function format?
My code:
<script>
var geocoder;
var map;
function initialize() {
var address = document.getElementById('address').value;
var latlng = GetLatLong(address);
alert(latlng);
var mapOptions = {
zoom: 8,
center: latlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function GetLatLong(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(results[0].geometry.location)
return results[0].geometry.location;
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I have a div for the address text and a div for the map location. To debug I put alert("") in some places to see the order in which it gets called on runtime, why would the line I put the first alert be called before the function is called?
Thanks
The Google Maps API call that you are performing is asynchronous. In layman's terms that means that as soon as you start the call, the rest of your program keeps executing independent of it. It is essentially running to the side of the rest of your program. The purpose of the function that you pass to the geocoder call is to deal with the data that the call returns asynchronously.
You would need to change your code to do something like this:
function initialize() {
var address = document.getElementById('address').value;
GetLatLong(address);
}
var map;
function GetLatLong(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(results[0].geometry.location)
var latlng = results[0].geometry.location;
var mapOptions = {
zoom: 8,
center: latlng
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
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.
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.