How can i limited the distance at the Google Places API search? - google-places-api

How can I limited the distance at the Google Places API search? He found places so far from me I want to limit the distance from me to the place.

var input = document.getElementById('id');
var autocompleteOptions = {
//types: ['(cities)'],
componentRestrictions: {country: "us"}
};
var autocomplete = new google.maps.places.Autocomplete(input,autocompleteOptions);

Related

AmCharts AmMap - Set starting location for zoom actions

I would like to use the "zoomToMapObject" method based on a selection on a dropdown menu.
For some reason the start zoom location is the middle of the map and not the set the geoPoint.
(The zooming works but the start location make it look a bit weird.)
My current approach looks like this:
const duration = this.chart.zoomToMapObject(selectedPoloygon, this.countryZoom, true).duration;
setTimeout(() => {
this.chart.homeGeoPoint = geoPoint;
this.chart.homeZoomLevel = this.countryZoom;
}, duration);
this.handleCountrySelection(selectedPoloygon);
Somehow even setting the homeGeoPoint / homeZoomLevel doesn't affect next zoom actions.
**UPDATE: Workaround heavy cost (from 1300 nodes to over 9000) **
I examined the problem a step further. It seems the middle point gets set when I push a new mapImageSeries into the map.
My workarround currently is to draw all points on the map and hide them.
Then after I select a country I change the state to visible.
However this approach is very costly. The DOM-Nodes rises from 1300 to ~ 9100.
My other approach with creating them after a country has been selected AND the zoom animation finished was much more
effective. But due to the map starting every time for a center location it is not viable? Or did I do s.th. wrong?
Here is my current code which is not performant:
// map.ts
export class MapComponent implements AfterViewInit, OnDestroy {
imageSeriesMap = {};
// ... standard map initialization ( not in zone of course )
// creating the "MapImages" which is very costly
this.dataService.getCountries().forEach(country => {
const imageSeriesKey = country.id;
const imageSeriesVal = chart.series.push(new am4maps.MapImageSeries()); // takes arround 1-2 ms -> 300 x 2 ~ 500 ms.
const addressForCountry = this.dataService.filterAddressToCountry(country.id); // returns "DE" or "FR" for example.
const imageSeriesTemplate = imageSeriesVal.mapImages.template;
const circle = imageSeriesTemplate.createChild(am4core.Circle);
circle.radius = 4;
circle.fill = am4core.color(this.colorRed);
circle.stroke = am4core.color('#FFFFFF');
circle.strokeWidth = 2;
circle.nonScaling = true;
circle.tooltipText = '{title}';
imageSeriesTemplate.propertyFields.latitude = 'latitude';
imageSeriesTemplate.propertyFields.longitude = 'longitude';
imageSeriesVal.data = addressForCountry.map(address => {
return {
latitude: Number.parseFloat(address.lat),
longitude: Number.parseFloat(address.long),
title: address.company
};
});
imageSeriesVal.visible = false;
this.imageSeriesMap[imageSeriesKey] = imageSeriesVal;
});
// clicking on the map
onSelect(country) {
this.imageSeriesMap[country].visible = true;
setTimeout( () => {
const chartPolygons = <any>this.chart.series.values[0];
const polygon = chartPolygons.getPolygonById(country);
const anim = this.chart.zoomToMapObject(polygon, 1, true, 1000);
anim.events.on('animationended', () => {});
this.handleCountrySelection(polygon);
}, 100);
});
}
handleCountrySelection(polygon: am4maps.MapPolygon) {
if (this.selectedPolygon && this.selectedPolygon !== polygon) {
this.selectedPolygon.isActive = false;
}
polygon.isActive = true;
const geoPoint: IGeoPoint = {
latitude: polygon.latitude,
longitude: polygon.longitude
};
this.chart.homeGeoPoint = geoPoint;
this.chart.homeZoomLevel = this.countryZoom;
this.selectedPolygon = polygon;
}
}
Thanks to your thorough followup I was able to replicate the issue. The problem you were having is triggered by any one of these steps:
dynamically pushing a MapImageSeries to the chart
dynamically creating a MapImage via data (also please note in the pastebind you provided, data expects an array, I had to change that while testing)
In either step, the chart will fully zoom out as if resetting itself. I'm going to look into why this is happening and if it can be changed, so in the meantime let's see if the workaround below will work for you.
If we only use a single MapImageSeries set in advance (I don't particularly see a reason to have multiple MapImageSeries, would one not do?), that eliminates problem 1 from occurring. Asides from data, we can create() MapImages manually via mapImageSeries.mapImages.create(); then assign their latitude and longitude properties manually, too. With that, problem 2 does not occur either, and we seem to be good.
Here's a demo with a modified version of the pastebin:
https://codepen.io/team/amcharts/pen/c460241b0efe9c8f6ab1746f44d666af
The changes are that the MapImageSeries code is taken out of the createMarkers function so it only happens once:
const mapImageSeries = chart.series.push(new am4maps.MapImageSeries());
const imageSeriesTemplate = mapImageSeries.mapImages.template;
const circle = imageSeriesTemplate.createChild(am4core.Circle);
circle.radius = 10;
circle.fill = am4core.color('#ff0000');
circle.stroke = am4core.color('#FFFFFF');
circle.strokeWidth = 2;
circle.nonScaling = true;
circle.tooltipText = 'hi';
In this case, there's no need to pass chart to createMarkers and return it, so I've passed polygon instead just to demo dynamic latitude/longitudes, I also assign our new MapImage to the polygon's data (dataItem.dataContext) so we can refer to it later. Here's the new body of createMarkers:
function createMarkers(polygon) {
console.log('calling createMarkers');
if ( !polygon.dataItem.dataContext.redDot) {
const dataItem = polygon.dataItem;
// Object notation for making a MapImage
const redDot = mapImageSeries.mapImages.create();
// Note the lat/long are direct properties
redDot.id = `reddot-${dataItem.dataContext.id}`;
// attempt to make a marker in the middle of the country (note how this is inaccurate for US since we're getting the center for a rectangle, but it's not a rectangle)
redDot.latitude = dataItem.north - (dataItem.north - dataItem.south)/2;
redDot.longitude = dataItem.west - (dataItem.west - dataItem.east)/2;;
dataItem.dataContext.redDot = redDot;
}
}
There's no need for the animationended event or anything, it just works since there is no longer anything interfering with your code. You should also have your performance back.
Will this work for you?
Original answer prior to question's edits below:
I am unable to replicate the behavior you mentioned. Also, I don't know what this.countryZoom is.
Just using the following in a button handler...
chart.zoomToMapObject(polygon);
...seems to zoom just fine to the country, regardless of the current map position/zoomLevel.
If you need to time something after the zoom animation has ended, the zoomToMapObject returns an Animation, you can use its 'animationended' event, e.g.
const animation = this.chart.zoomToMapObject(selectedPoloygon, this.countryZoom, true);
animation.events.on("animationended", () => {
// ...
});
Here's an example with all that with 2 external <button>s, one for zooming to USA and the other Brazil:
https://codepen.io/team/amcharts/pen/c1d1151803799c3d8f51afed0c6eb61d
Does this help? If not, could you possibly provide a minimal example so we can replicate the issue you're having?

Xamarin.Android Couchbase.Lite Map Reduce

I simply want to create a View that uses Map-Reduce to do this: Say I have Documents for the Automobile Industry. I would like the user to query for a particular Make - say Ford for example. I would like the user to provide the Ford value via an EditText, Tap a Button, and the "Count" be shown in a TextView. So, to clarify, I want to do a count of a certain type of Document using Map-Reduce. I have searched for over 100 hundred hours on this and have not found not one single example - REAL example I mean. (I have read all the docs, only generic examples - no actual examples)
I am an experienced programmer 15+ yrs exp - all I need is one example, and I am good to go.
Can someone please assist me with this?
Thanks,
Don
Here is my Actual Code:
string lMS = "MS:5"; // just to show what type of value I am using
var msCount = dbase.GetView ("count_ms");
msCount.SetMapReduce ((doc, emit) => {
if (doc.ContainsKey ("DT") && doc["DT"].Equals ("P")) {
if (doc.ContainsKey ("MS") && doc["MS"].Equals (_ms))
{
emit (doc ["id"], 1);
}
}
},
(keys, values, rereduce) => values.ToList().Count, "1");
var mscView = dbase.GetView ("count_ms");
var query = mscView.CreateQuery ();
query.StartKey = "MS:1";
query.EndKey = "MS:9999";
var queryResults = query.Run ();
var nr = queryResults.Count; // shows a value of 1 - wrong - should be 40
// the line below is to allow me to put a stop statement to read line above
var dummyForStop = nr;
Try setting something like
var docsByMakeCount = _database.GetView("docs_by_make_count");
docsByMakeCount.SetMapReduce((doc, emit) =>
{
if (doc.ContainsKey("Make"))
{
emit(doc["Make"], doc);
}
},
(keys, values, rereduce) => values.ToList().Count
, "1");
when you create your view.
and when you use it:
var docsByMake = _database.GetView("docs_by_make_count");
var query = docsByCity.CreateQuery();
query.StartKey = Make;
query.EndKey = Make;
var queryResults = query.Run();
MessageBox.Show(string.Format("{0} documents has been retrieved for that query", queryResults.Count));
if (queryResults.Count == 0) return;
var documents = queryResults.Select(result => JsonConvert.SerializeObject(result.Value, Formatting.Indented)).ToArray();
var commaSeperaterdDocs = "[" + string.Join(",", documents) + "]";
DocumentText = commaSeperaterdDocs;
In my case Make and DocumentText are properties.
There are some optimizations to be made here, like rereducing, but it's the straight forward way.

How to restrict google places to specific city

I am currently able to restrict places to only one country, but I also want to restrict on a specific city also. Any ideas how to achieve that? This is my current code:
var autocomplete,
options = {
types: ['geocode'],
componentRestrictions: {country: 'est'}
};
autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace().formatted_address;
$(input).attr('value',place);
});
As Luke said the places autocomplete allows you to use componentRestrictions to filter by country only.
But you can use a little trick with a search request string.
Just add prefix with city name in request.
var prefix = 'Kyiv, ';
$(input).on('input',function(){
var str = input.value;
if(str.indexOf(prefix) == 0) {
// string already started with prefix
return;
} else {
if (prefix.indexOf(str) >= 0) {
// string is part of prefix
input.value = prefix;
} else {
input.value = prefix+str;
}
}
});
http://jsfiddle.net/24p1et98/
Places Autocomplete currently allows you to use componentRestrictions to filter by country. What I would do in your situation is to use the options argument to filter by the bounds that define the city in question:
var cityBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(25.341233, 68.289986),
new google.maps.LatLng(25.450715, 68.428345));
var options = {
bounds: cityBounds,
types: ['geocode'],
componentRestrictions: {country: 'est'}
};
Google Provides two ways to achieve this. If you are not satisfied because in countries like India it do not work well, because states and provisions here do not have rectangular or structure boundaries.
1.LatLngBounds (LatLng southwest, LatLng northeast): Where you can give latitude and longitude to form an rectangle.
2. Location (Lat,Lng) & Radius: Where you can give latitude and longitude to form a circle.
But the problem with these approaches they do not provide expected results if you are from countries like India, where states and provisions are not in structured shapes (Rectangular) as in USA.
If you are facing same issue than there is an hack.
With jQuery/Jacascript, you can attach functions which will consistently maintain city name in text input which is bounded with Autocomplete object of Places API.
Here it is:
<script>
$(document).ready(function(){
$("#locality").val(your-city-name) //your-city-name will have city name and some space to seperate it from actual user-input for example: “Bengaluru | ”
});
$("#locality").keydown(function(event) { //locality is text-input box whixh i supplied while creating Autocomplete object
var localeKeyword = “your-city-name”
var localeKeywordLen = localeKeyword.length;
var keyword = $("#locality").val();
var keywordLen = keyword.length;
if(keywordLen == localeKeywordLen) {
var e = event || window.event;
var key = e.keyCode || e.which;
if(key == Number(46) || key == Number(8) || key == Number(37)){
e.preventDefault();
}//Here I am restricting user to delete city name (Restricting use of delete/backspace/left arrow) if length == city-name provided
if(keyword != localeKeyword) {
$("#locality").val(localeKeyword);
}//If input-text does not contain city-name put it there
}
if(!(keyword.includes(localeKeyword))) {
$("#locality").val(localeKeyword);
}//If keyword not includes city name put it there
});

Maps API: Finding the longest common path in two given paths

Google maps and Bing maps have methods that can give the directions from point A to point B on a map. This highlights a path from A to B on the map - call this P1
Suppose, P2 is another path from C to D (some other points), how can we find the longest common length of path between paths P1 and P2?
You have plenty of ways to do what you want.
Curiously, I tried to do it using JavaScript only and to do so, I used JSTS library that would compute the intersection between two routes (in my case, the geometry were retrieved from Bing, but I did not include the request in this example as it's not helpful).
Use case:
So, you want to have the common path between two paths (or the part of a route where you can use car-sharing or where you can run with your friend for example), if this is correct, then this example will help you.
Libraries:
First, the following library is need: JSTS, you can get it through Github dedicated repository: https://github.com/bjornharrtell/jsts
On other interesting library is Turf available here: https://github.com/Turfjs/
Implementation with JSTS and leaflet:
Here is the piece of JavaScript that will be interesting in this case:
<script type="text/javascript">
var routeCoordinatesA = [[50.619512, 3.061242]....TRUNCATED FOR READIBILITY** ];
var routeCoordinatesB = [[50.619512, 3.061242]....TRUNCATED FOR READIBILITY** ];
$(function () {
var map = L.map('map').setView([47.5, 2.75], 5);
// Add base tile layer - sample from Leaflet website
L.tileLayer('http://{s}.tile.thunderforest.com/transport/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var polylineA = L.polyline(routeCoordinatesA, { color: '#4b98dc' }).addTo(map);
var polylineB = L.polyline(routeCoordinatesB, { color: '#de6262' }).addTo(map);
var geometryFactory = new jsts.geom.GeometryFactory();
// Coordinates adapted to match for jsts
var coordsA = [];
$.each(routeCoordinatesA, function (idx, current) { coordsA.push([current[1], current[0]]); });
var coordsB = [];
$.each(routeCoordinatesB, function (idx, current) { coordsB.push([current[1], current[0]]); });
// Element A
var coordinatesA = bindCoord2JTS(coordsA);
var shellA = geometryFactory.createLinearRing(coordinatesA);
var jstsPolygonA = geometryFactory.createPolygon(shellA);
// Element b
var coordinatesB = bindCoord2JTS(coordsB);
var shellB = geometryFactory.createLinearRing(coordinatesB);
var jstsPolygonB = geometryFactory.createPolygon(shellB);
// Interection
var bufferTolerance = (2 / 1000); // Small buffer to avoid different node no detection
var intersection = shellA.buffer(bufferTolerance).intersection(shellB);
var intersectionPoints = [];
$.each(intersection.getCoordinates(), function (idx, current) {
intersectionPoints.push([current.x, current.y]);
});
intersectionPoints.pop();
var intersectionLine = L.polyline(intersectionPoints, { color: '#4fc281', weight: 8 }).addTo(map);
map.fitBounds(routeCoordinatesA.concat(routeCoordinatesB));
});
var bindCoord2JTS = function (coords) {
var coordinates = [];
for (var i = 0; i < coords.length; i++) {
coordinates.push(new jsts.geom.Coordinate(
coords[i][1], coords[i][0]));
}
return coordinates;
};
You can grab all the working example among my Leaflet experiments available on Github as well:
https://github.com/nicoboo/maps/tree/master
And here the page that implements what I was talking about:
https://github.com/nicoboo/maps/blob/master/Boo.Maps.Web.LeafletExperiments/LeafletWithin/index.html
Here for the live demo: http://htmlpreview.github.io/?https://github.com/nicoboo/maps/blob/master/Boo.Maps.Web.LeafletExperiments/LeafletWithin/index.html
Considerations:
Of course, this is really based on the client side and it might be usefull to have the information on the server-side, I would recommend to use a spatially enabled database so you can use the STBuffer() and STIntersection() methods directly on the column or results that you manipulate with the best performances.
I am not sure to fully understand your request but both Bing maps ans Google maps API for the directions contains in their response a "distance" field which specifies the value of the directions.
Here are two links for both documentation:
Bing Maps & Google Maps
With that you could compare the distance value between the two path and find the longest.
Hope this help.

Get Marker on Google Maps via name of Business

I am building a website, and on it I have a Google Map. I also have a list of business names, e.g. WH Smith, Manchester.
Assuming there is only one in Manchester, how can I get a Marker showing on my Map the location of the WH Smith branch?
I tried searching, but found nothing on the subject !
The way I do it is to set up an array of locations, each of which is an array of the necessary information, in the order html for tooltip, latitude, longitude, title. I get the Latitude and Longitude from this site: http://universimmedia.pagesperso-orange.fr/geo/loc.htm So you would just type in the city center.
function initialize() {
geocoder = new google.maps.Geocoder();
var businesslocations = [
['HTML TO DISPLAY ON TOOLTIP', LATITUDE, LONGITUDE,'LOCATION NAME'],
['HTML TO DISPLAY ON TOOLTIP', LATITUDE, LONGITUDE,'LOCATION NAME'],
Finish that array off, then do your other map settings. Then set up the map. Then set up its markers programmatically using that array. The for loop goes through the different locations, and then pulls out the 4 elements of the array.
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
var marker, x;
for (x = 0; x < businesslocations.length; x++) {
var latllong = new google.maps.LatLng(businesslocations[x][1], businesslocations[x][2]);
marker = new google.maps.Marker({
position: latlong,
map: map,
title: businesslocations[i][3]
});
bounds.extend(latlong);
google.maps.event.addListener(marker, 'click', (function(marker, x) {
return function() {
infowindow.setContent(businesslocations[x][0]);
infowindow.open(map, marker);
}
})(marker, x));
}
map.fitBounds(bounds);

Resources