I am trying to create an autocomplete text field which should only provide the postal code in dropdown. Here is the documentation which I have followed:
google place autocomplete
How do i get only and all the postcodes of UK over there.
src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"
src="https://maps.googleapis.com/maps/api/js?key=your_api_key&libraries=places&sensor=false&callback=initialize"
function initialize() {
$('#adv_postcode').each(function () {
initialize2(this);
});
}
function initialize2(elementID) {
var options = {
componentRestrictions: {
country: 'uk'
}
};
var autocomplete_element = new google.maps.places.Autocomplete(elementID, options);
autocomplete_element.addListener('place_changed', function () {
elementID.value = fillInAddress(autocomplete_element);
});
}
<input type="text" name="adv_postcode" id="adv_postcode" class="addressfields"/>
Any help highly appreciated
At the moment the best option that you have is setting types parameter of autocomplete options to (regions). According to the documentation
The (regions) type collection instructs the Places service to return any result matching the following types:
locality
sublocality
postal_code
country
administrative_area_level_1
administrative_area_level_2
source: https://developers.google.com/places/supported_types#table3
Not ideal, but you will get only regions in the list of suggestions. So your code should be
var options = {
componentRestrictions: {
country: 'uk'
},
types: ['(regions)']
};
var autocomplete_element = new google.maps.places.Autocomplete(elementID, options);
autocomplete_element.addListener('place_changed', function () {
elementID.value = fillInAddress(autocomplete_element);
});
Also, note that there is a feature request in Google issue tracker to make types parameter more flexible:
https://issuetracker.google.com/issues/35820774
Feel free to star this feature request to express your interest and subscribe to notifications.
Related
I am using Wikidata API to get birth location from famous people, and then displaying the location using Google Maps API. Here is the Wikidata request I use :
SELECT DISTINCT ?item ?itemLabel ?birthLocation ?birthLocationLabel WHERE {
?item (wdt:P31|wdt:P101|wdt:P106)/wdt:P279* wd:Q482980 ;
rdfs:label "Mary Wollstonecraft"#en ;
wdt:P19 ?birthLocation
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
I'm then using a google geocoder to get a lat lng from the birthLocationLabel, and displaying it on the map, however sometimes the geocoder can't find a location (maybe the place doesn't exist anymore), so I'd like to know if it was possible to get coordinates from the wikidata query ? I know birth location has a "coordinate location" property, but I don't know how to access it.
Here is the link of the wikidata query
This works for me ?birthLocation wdt:P625 ?coordinates so the whole query would be:
SELECT DISTINCT ?item ?itemLabel ?coordinates ?birthLocation ?birthLocationLabel
WHERE {
?item ((wdt:P31|wdt:P101|wdt:P106)/(wdt:P279*)) wd:Q482980;
rdfs:label "Mary Wollstonecraft"#en;
wdt:P19 ?birthLocation.
?birthLocation wdt:P625 ?coordinates.
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
This returns:
[{
"item": "http://www.wikidata.org/entity/Q101638",
"itemLabel": "Mary Wollstonecraft",
"coordinates": "Point(-0.075 51.5166)",
"birthLocation": "http://www.wikidata.org/entity/Q123219",
"birthLocationLabel": "Spitalfields"
}]
I want to get the currency code information (for example:USD etc.) from country code.I tried most of methods but I cannot have this data.I had the country code from geolocation.
How can I solve this problem and get the currency code?
Copy the object in this page into your code, like this
var countryCurrencies = {
"BD": "BDT",
"BE": "EUR",
"BF": "XOF",
...
"UA": "UAH",
"QA": "QAR",
"MZ": "MZN"
}
//get your country code
var countryCode = "ma"; //For example
var currency = countryCurrencies.hasOwnProperty(countryCode.toUpperCase()) ? countryCurrencies[countryCode.toUpperCase()] : "Unkonw";
//The result : curreny = "MAD"
You can do with this following api its very easy and good
https://restcountries.eu/rest/v1/alpha/in
"in" be the country code for india.
Eg with jquery
jQuery.getJSON(
"https://restcountries.eu/rest/v1/alpha/in,
function (data) {
console.log(data.currencies)
}
);
in data: you get almost every information related to country
Here an Array with all Country Information:
<?php $location = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR'])); print_r($location) ?>
I'm using Google Maps autocomplete feature and everything is working fine.
But I'd like to know if it's possible to run .getPlace() function from a custom string, wether it's coordinates or address. For example, instead of using an input field and click on the location to select it, I'd like to call it manually, like this:
var myAutoComplete = new google.maps.places.Autocomplete('City, Country');
And it return the same as a normal autocomplete. The reason why I want to do this, is because somethis I get users location from html5 geolocation (or other method) and I'd like to run the getPlace function with that data.
The getPlace function from google return a more complete set of data, with all the names, coordinates, pictures from that city, etc..
By the way, I'm using Google Maps with AngularJs with this module: ngMap.
Edit: Posting the code I have so far as requested on the comments.
//HTML
<input places-auto-complete on-place-changed="vm.placeChanged()" />
//Controller
function MainController(NgMap) {
var vm = this;
vm.placeChanged = function() {
var param = {
maxWidth: 1920,
maxHeight: 1080
};
var autocomplete = this.getPlace();
console.log('Result: ', autocomplete);
console.log(autocomplete.geometry.location.lat());
console.log(autocomplete.geometry.location.lng());
console.log(autocomplete.photos[0].getUrl(param));
}
}
The input automatically generate the autocomplete feature, when I select one address option, the function is called and I get all the response correctly.
What I want is to call the same function, but instead of using the autocomplete from google, I want to pass my own string and return the same data as the function.
As suggested on the comments, I tried using a custom directive to run the same autocomplete, this is my plunkr: http://plnkr.co/edit/hcRXJxB7ItN6YtISWdx3?p=preview
Autocomplete object does not support such kind of scenario, it could only be attached to the specified input text field from where the user selects the item and the correspinding place is returned.
Instead you could utilize AutocompleteService class which in my opinion suits your scenario very closely
According to official documentation AutocompleteService class
does not add any UI controls. Instead, it returns an array of
prediction objects, each containing the text of the prediction,
reference information, and details of how the result matches the user
input. This is useful if you want more control over the user interface
than is offered by the Autocomplete
The following example demonstrates how to return the details of the Place from input string entered in text box
Example
var app = angular.module('myApp', ['ngMap']);
app.controller('MyCtrl', function ($scope,NgMap) {
var vm = this;
vm.center = [0,0];
vm.types = "['establishment']";
NgMap.getMap().then(function (map) {
vm.map = map;
});
vm.addressResolved = function (value) {
$scope.$apply(function () {
vm.address = value.address_components;
vm.center = value.geometry.location;
});
}
});
app.directive('myComplete', function (NgMap) {
return {
restrict: 'A',
scope: {
map: '=',
addressResolved: '&addressResolved'
},
link: function (scope, element, attrs) {
// on blur, update the value in scope
element.bind('blur', function (blurEvent) {
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({ input: element.val() }, function (predictions, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
if (predictions.length > 0) {
element.val(predictions[0].description);
var service = new google.maps.places.PlacesService(scope.map);
service.getDetails({
placeId: predictions[0].place_id
}, function (place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
scope.addressResolved({ place: place });
}
});
}
}
});
});
}
};
});
<script src="https://maps.google.com/maps/api/js?libraries=placeses,visualization,drawing,geometry,places"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl as vm">
Auto Complete Type:
<select ng-model="vm.types">
<option value="['geocode']">Geodode</option>
<option value="['establishment']">Establishment</option>
<option value="['address']">Address</option>
</select><br/>
<h3>Custom directive usage</h3>
<input my-complete address-resolved="vm.addressResolved(place)" map="vm.map" />
address : <pre>{{vm.address | json}}</pre>
<ng-map zoom="12" center="{{vm.center}}"></ng-map>
</div>
Demo
I have JSON field like
{"facebook":"aravind#facebook.com",
"homeAddress":"26, New Street, Blr",
"officeAddress":"31, Old Office Street, Blr",
"city":"Blr",
name:"aravind"
},
{"facebook":"ashok#facebook.com",
"homeAddress":"26, New Street, che",
"officeAddress":"31, Old Office Street, che",
"city":"che",
name:"ashok"
}
In Angular js, I have ordered the field by name defaultly, I have one text box and button
<input type="text" class="form-control" ng-model="search.location" />
<div class="search" ng-click="locationSorting()"></div>
When i click the button after enter the location in text box( For Ex: blr). The list is sorted by location.
Currently i have finishing the filter by location. But i dont want filtering. I want sorting the list
var locationFilterHome = {homeAddress: location};
filterData = $filter('filter')(data, locationFilterOffice)
I am using above code for filtering. How to do sorting based on location
From what I understand, you wish to ask how to sort the data by location in the controller.
One way would be to use the 'orderBy' filter. You can use it just like you use the 'filter' filter: filterData=$filter('orderBy')(data,'location');
Please check out this plunk for an example of what I am trying to say: http://plnkr.co/edit/BU4DaxlBSNcmRkXG6krc?p=preview
angular.module('app',[])
.controller('mainCtrl',function($filter){
var data=[{"facebook":"aravind#facebook.com",
"homeAddress":"26, New Street, Blr",
"officeAddress":"31, Old Office Street, Blr",
"city":"Zlr",
name:"aravind"
},
{"facebook":"ashok#facebook.com",
"homeAddress":"26, New Street, che",
"officeAddress":"31, Old Office Street, che",
"city":"che",
name:"ashok"
}];
var modifiedData=$filter('orderBy')(data,'city');
console.log(modifiedData);
})
Your can create filter like this way!!
`bizBrainCommon.filter('test', function () {
return function (items, field, sortingValue) {
var filtered = [];
if(!field || !sortingValue)
return items;
angular.forEach(items, function (item) {
filtered.push(item);
});
filtered.sort(function (a, b) {
var upA = a[field].toUpperCase();
if (upA > sortingValue.toUpperCase() || upA < sortingValue.toUpperCase()) return 1;
if (upA == sortingValue.toUpperCase())
return -1;
});
return filtered;
};
});`
HTML will be like:
ng-repeat="(id, user) in users |test:'fName': search"
Hope this will help you!!
Trying to figure out how to do this, using Sanderson begincollectionitems method, and would like to use autocomplete with a field in each row.
I think I see how to add a row with an autocomplete, just not sure the approach for existing rows rendered with guid.
Each row has an of field that the user can optionally point to a record in another table. Each autocomplete would need to work on the html element idfield_guid.
I'm imagining using jquery to enumerate the elements and add the autocomplete to each one with the target being the unique of field for that row. Another thought is a regex that maybe let you enumerate the fields and add autocomplete for each in a loop where the unique field id is handled automatically.
Does that sound reasonable or can you suggest the right way? Also is there a reasonable limit to how many autocomplete on a page? Thanks for any suggestions!
Edit, here's what I have after the help. data-jsonurl is apparently not being picked up by jquery as it is doing the html request to the url of the main page.
$(document).ready(function () {
var options = {
source: function(request, response) {
$.getJSON($(this).data("jsonurl"), request, function (return_data) {
response(return_data.itemList);
});
},
minLength: 2
};
$('.ac').autocomplete(options);
});
<%= Html.TextBoxFor(
x => x.AssetId,
new {
#class = "ac",
data_jsonurl = Url.Action("AssetSerialSearch", "WoTran", new { q = Model.AssetId })
})
%>
And the emitted html look okay to me:
<input class="ac" data-jsonurl="/WoTran/AssetSerialSearch?q=2657" id="WoTransViewModel_f32dedbb-c75d-4029-a49b-253845df8541__AssetId" name="WoTransViewModel[f32dedbb-c75d-4029-a49b-253845df8541].AssetId" type="text" value="2657" />
The controller is not a factor yet, in firebug I get a request like this:
http://localhost:58182/WoReceipt/Details/undefined?term=266&_=1312892089948
What seems to be happening is that the $(this) is not returning the html element but instead the jquery autocomplete widget object. If I drill into the properties in firebug under the 'element' I eventually do see the data-jsonurl but it is not a property of $(this). Here is console.log($this):
You could use the jQuery UI Autocomplete plugin. Simply apply some know class to all fields that require an autocomplete functionality as well as an additional HTML5 data-url attribute to indicate the foreign key:
<%= Html.TextBoxFor(
x => x.Name,
new {
#class = "ac",
data_url = Url.Action("autocomplete", new { fk = Model.FK })
})
%>
and then attach the plugin:
var options = {
source: function(request, response) {
$.getJSON($(this).data('url'), request, function(return_data) {
response(return_data.suggestions);
});
},
minLength: 2
});
$('.ac').autocomplete(options);
and finally we could have a controller action taking two arguments (term and fk) which will return a JSON array of suggestions for the given term and foreign key.
public ActionResult AutoComplete(string term, string fk)
{
// TODO: based on the search term and the foreign key generate an array of suggestions
var suggestions = new[]
{
new { label = "suggestion 1", value = "suggestion 1" },
new { label = "suggestion 2", value = "suggestion 2" },
new { label = "suggestion 3", value = "suggestion 3" },
};
return Json(suggestions, JsonRequestBehavior.AllowGet);
}
You should also attach the autocomplete plugin for newly added rows.