searchBox Google Maps with pagination - javascript

So what I am trying to do is implement Google Maps with a search box. Currently, the search box retrieves 20 of the top places based on the search result.
What I noticed is there is no pagination with this. Such as if I type in “pizza”, it will give me the top 20 results in the current location bounds. But when I use the google.maps.places.PlacesService(map) textSearch function to obtain a list of pizza searches, I get more than 20 results with pagination.
Is there a way to get pagination on your searchBox or use the textSearch function to provide pagination after you used searchBox?
What I have here is a snippet:
var canvas = element.find('div')[0];
var mapOptions = {
zoom: 5,
minZoom: 2,
};
var searchBox = new google.maps.places.SearchBox('pizza');
var placeService = new google.maps.places.PlacesService(map);
google.maps.event.addListener(searchBox, 'places_changed', locationChange);
function locationChange() {
var places = searchBox.getPlaces();
//Determine if there are additional places not provided by searchbox. Using text
var request = {
query: input.value,
};
var textSearchPlaces = placeService.textSearch(request, callback);
function callback(results, status, pagination) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var hi = places;
for (var i = 0; i < results.length; i++) {
var place = results[i];
}
}
}
if (places.length === 0) {
return;
}
};
As you can see this is not the most ideal solution to looking using a pagination as I would have to filter through the textSearchPlaces to see if those places are not duplicates of the searchBox results.
I also thought about just removing the searchBox and just going with the textSearch function but I realized I wouldn’t have the autoComplete function that provides suggestions that searchBox provides.

Most likely you are getting OVER_QUERY_LIMIT.
if (status == google.maps.places.PlacesServiceStatus.OK) {
Try queuing the details requests for after you have all the list completed, adding the same timeout logic to check for google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT on this line.
if (pagination.hasNextPage) {
//add all places to the list
setTimeout('pagination.nextPage()',2000);
} else {
createMarkers(placesList);
}
You should use google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT when using Places.

Related

Trouble getting custom pin to show in Bing Map

I'm showing using a bing map on my web page and I'm trying to use a custom pin for the location but it won't show up. My project is ASP.Net Core, My image is stored in wwwroot/images and this JavaScript is in wwwroot/js/site.js. I'm not sure if my path is just wrong or what.
var renderRequestsMap = function (divIdForMap, requestData) {
if (requestData) {
var bingMap = createBingMap(divIdForMap);
addRequestPins(bingMap, requestData);
}
}
function createBingMap(divIdForMap) {
var map = new Microsoft.Maps.Map(
document.getElementById(divIdForMap), {
credentials: BingMapKey,
zoom: 2
});
// tile url from Iowa Environmental Mesonet of Iowa State University
var urlTemplate = 'https://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-{timestamp}/{zoom}/{x}/{y}.png';
var timestamps = ['900913-m50m', '900913-m45m', '900913-m40m', '900913-m35m', '900913-m30m', '900913-m25m', '900913-m20m', '900913-m15m', '900913-m10m', '900913-m05m', '900913'];
var tileSources = [];
for (var i = 0; i < timestamps.length; i++) {
var tileSource = new Microsoft.Maps.TileSource({
uriConstructor: urlTemplate.replace('{timestamp}', timestamps[i])
});
tileSources.push(tileSource);
}
var animatedLayer = new Microsoft.Maps.AnimatedTileLayer({ mercator: tileSources, frameRate: 500 });
map.layers.insert(animatedLayer);
return map;
}
function addRequestPins(bingMap, requestData) {
var locations = [];
$.each(requestData, function (index, data) {
var location = new Microsoft.Maps.Location(data.lat, data.long);
locations.push(location);
var order = index + 1;
alert(data.pinurl);
var pin = new Microsoft.Maps.Pushpin(location, { icon: 'images/low-risk-south-pin.png' });
bingMap.entities.push(pin);
});
var rect = Microsoft.Maps.LocationRect.fromLocations(locations);
bingMap.setView({ bounds: rect, padding: 80 });
}
Also when the map loads it is super zoomed into my pin and whatever I do I can't get it to start with a far out zoom.
If you can, take a look at the network trace. Here you should see where the images are being requested from and will help you verify if it is requesting from the right location.
As for the zooming, you are calculating in the LocationRect from the locations of the pins and then setting the map view based on that. Sounds like that is working as expected. If you don't want to zoom in on your pins, remove that code.

Bing Maps Directions Callback Runs Too Fast?

When using the Bing Maps Api and doing geocoding I am trying to store the latitude and longitude in arrays from the callback. Mostly this works, except for one usually. There always seems to be a duplicate latitude and longitude in entitiesToVisit, but not testLocations when CalculateOptimizedDirections is called.
for(var i = 0; i < toVisit.length; i++){
if(toVisit[i].checked){
var count = parseInt(toVisit[i].id.toString().split(":")[0]);
var tempEntity = entitiesToPickFrom[count];
console.log(entitiesToPickFrom[count]);
tempEntity.compositeAddress = document.getElementById("d"+toVisit[i].id.toString().split(":")[1]).innerHTML.split(">")[1].split("<")[0];
config.searchManager.geocode({
where: tempEntity.compositeAddress,
count: 1,
callback: function (result, pinData) {
var topResult = result.results && result.results[0];
if (topResult) {
pinData.latitude = topResult.location.latitude;
pinData.longitude = topResult.location.longitude;
entitiesToPickFrom[count].latitude = topResult.location.latitude;
entitiesToPickFrom[count].longitude = topResult.location.longitude;
//entitiesToVisit.push(pinData);
//setTimeout(10,function (){console.log("Pin Data");});
//console.log(entitiesToVisit);
document.getElementById("BingMap").style.display = "block";
var wizardDiv = document.getElementById("AddressSelectioWizard");
wizardDiv.style.display = "none";
//possible issue
testLocations.push(new Microsoft.Maps.Location(pinData.latitude,pinData.longitude));
entitiesToVisit.push(pinData);
//testLocations.push(new Microsoft.Maps.Directions.Waypoint(tempEntity.latitude,tempEntity.longitude));
if(entitiesToVisit.length >= checkedCheckers){
CalculateOptimizedDirections();
}
}
else{
//console.log("Nothing gotten");
console.log(result);
//console.log(tempEntity.compositeAddress);
}
},
errorCallback: function (error){console.log(error)},
userData: tempEntity
});
}
}
I've noticed that when I set a timeout to just print text to the console in the middle of the callback, everything works perfectly. This seems to be a bad solution though, is there a better way around it?
The pinData object you are passing into the entitiesToVisit array is the tempEntity value you are passing into the userData option of the geocode call. The issue is likely related to this code:
var count = parseInt(toVisit[i].id.toString().split(":")[0]);
var tempEntity = entitiesToPickFrom[count];

PlacesService's text search not consistent with Autocomplete

We're seeing an issue where the PlacesService's textSearch is not returning any results for the "Strood Station Car Park, Rochester", whereas the Autocomplete is. I've created this JS Fiddle that shows the demonstrates this behavior: http://jsfiddle.net/anero/b5jh56gy/6/
Is there a way to have a consistent result set for both API calls?
var client = new google.maps.places.PlacesService($("#google-attributions")[0]);
var query = "Strood Station Car Park, Rochester";
var textSearchRequest = {
query: query
};
client.textSearch(textSearchRequest, function (response, status) {
if (status === google.maps.GeocoderStatus.OK && response.length > 0) {
alert('Found place!');
} else {
alert('Did not find place!');
}
});

how do I get the number of markers currently on google maps v3?

I'm using Google maps v3 and I am wondering if it is possible to call a function that returns the number of markers currently on that map regardless of zoom.
The API doesn't have a function of the form getAllMarkers(). So, handle them from the start with:
var myMarkers = [];
for(var i = 0; i < 10; i++) {
var marker = new google.maps.Marker(...);
myMarkers.push(marker);
}
// process, delete myMarkers
function getAllMarkers ()
{
alert("size: " + myMarkersArray.length());
}

Update Google Places API results using javascript

I'm using Google Places API to get location details using javascript.
var request = {
input: request.term,
componentRestrictions: {country: 'us'},
types: ['geocode']};
service.getPlacePredictions(request, function (predictions, status) {
if (status != 'OK') {
return;
}
response($.map(predictions, function (prediction, i) {
var cty_st = '';
var pred_terms_lnt = prediction.terms.length;
if(pred_terms_lnt >= 3){
cty_st = prediction.terms[pred_terms_lnt - 3].value+', '+prediction.terms[pred_terms_lnt - 2].value;
}
else if(pred_terms_lnt >= 2){
cty_st = prediction.terms[pred_terms_lnt - 2].value;
}
else{
cty_st = prediction.description.replace(", United States", "");
}
return {
label: cty_st,
value: cty_st,
ref: prediction.reference,
id: prediction.id
}
}));
});
I want to show only city and state code from the results fetched and when I search for a location I'm getting duplicate city, state coder in the results. I want to remove these duplicates from the results. How to do that?
From the above results you can see last two results have same city and state code. I want to show only once.
Instead of types: ['geocode'] use types: ['(cities)']

Categories