Hi I am using the following code to display the user current position on the map:
function drawMap() {
var latlng = new google.maps.LatLng(currentLatitude, currentLongitude);
myLatLng = latlng;
var mapOptions = {
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.LEFT_TOP
},
};
if (boolTripTrack === true) {
_map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
}
var suc = function(p) {
console.log("geolocation success", 4);
//Draws the map initially
if (_map === null) {
currentLatitude = p.coords.latitude;
currentLongitude = p.coords.longitude;
drawMap();
//reverseGeocode(currentLatitude, currentLongitude);
} else {
myLatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
}
//Creates a new google maps marker object for using with the pins
if ((myLatLng.toString().localeCompare(oldLatLng.toString())) !== 0) {
//Create a new map marker
var Marker = new google.maps.Marker({
position: myLatLng,
map: _map
});
if (_llbounds === null) {
//Create the rectangle in geographical coordinates
_llbounds = new google.maps.LatLngBounds(new google.maps.LatLng(p.coords.latitude, p.coords.longitude)); //original
} else {
//Extends geographical coordinates rectangle to cover current position
_llbounds.extend(myLatLng);
}
//Sets the viewport to contain the given bounds & triggers the "zoom_changed" event
_map.fitBounds(_llbounds);
}
oldLatLng = myLatLng;
};
var fail = function() {
console.log("Geolocation failed. \nPlease enable GPS in Settings.", 1);
};
var getLocation = function() {
console.log("in getLocation", 4);
};
This works fine but I need to perform reverse geocoding when a button is pressed so that the address is displayed. The function is am using is:
function reversegeocode(){
var latlng = new google.maps.LatLng(?, ?);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert(results[1].formatted_address);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
I am unsure of how to pass in the current latitude and longitude from the previous function. Can anyone help me with this??
Thank you..
Define the reverse geocode function like this, with parameters for lat and lng:
function reversegeocode(lat, lng){
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert(results[1].formatted_address);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
And then call the function by passing the variables : reverseGeocode(currentLatitude, currentLongitude);
Related
I have a page where I need to load a Map by an address to see the property located at that point. To do this I found the Google Maps API but I cannot do this works yet. I'm trying an example that I saw on documentation but it still doesn't works and does not throws any exception.
Here de documentation.
How could I do this ?
Loading Google Maps API
<script src="https://maps.google.com/maps/api/js?key=AIzaSyA8JZPv2N9bE0OQABj6hKO9QZb0kH32l"></script>
Script to Load Map By Address
$(document).ready(function () {
initialize();
codeAddress();
});
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('gmap'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('myAddress').value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
HTML
<div id="gmap"></div>
<!--my address-->
#Html.HiddenFor(model => model.myAddress)
I finally solved the problem.
function loadByAddress() {
var address = $('#myAddress').val();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == 'OK') {
var latlng = new google.maps.LatLng(results[0].geometry.location.lat, results[0].geometry.location.lng);
var myOptions = {
zoom: 20,
center: latlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("gmap"), myOptions);
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", loadByAddress);
I am developing a mvc5 web application. I am trying to store the user's location (Latitude, Longitude) to a database. I can save the location name. But, i can't save latitude and longitude info. How can i insert these?
Thanks for your help.
listing.Cshtml file:
<fieldset>
<legend>[[[Location]]]</legend>
<div class="form-group">
<label>[[[Location]]]</label>
<input type="text" class="form-control input-lg" placeholder="[[[Enter Location]]]" id="Location" name="Location" value="#Model.ListingItem.Location">
</div>
<input type="hidden" id="Longitude" name="Longitude" value="#Model.ListingItem.Longitude" />
<input type="hidden" id="Latitude" name="Latitude" value="#Model.ListingItem.Latitude" />
<div class="form-group">
<div id="map-canvas"></div>
</div>
</fieldset>
listingController:
[HttpPost]
[AllowAnonymous]
public async Task<ActionResult> ListingUpdate(Listing listing, FormCollection form, IEnumerable<HttpPostedFileBase> files)
{
if (CacheHelper.Categories.Count == 0)
{
TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
TempData[TempDataKeys.UserMessage] = "[[[There are not categories available yet.]]]";
return RedirectToAction("Listing", new { id = listing.ID });
}
var userIdCurrent = User.Identity.GetUserId();
// Register account if not login
if (!User.Identity.IsAuthenticated)
{
var accountController = BeYourMarket.Core.ContainerManager.GetConfiguredContainer().Resolve<AccountController>();
var modelRegister = new RegisterViewModel()
{
Email = listing.ContactEmail,
Password = form["Password"],
ConfirmPassword = form["ConfirmPassword"],
};
// Parse first and last name
var names = listing.ContactName.Split(' ');
if (names.Length == 1)
{
modelRegister.FirstName = names[0];
}
else if (names.Length == 2)
{
modelRegister.FirstName = names[0];
modelRegister.LastName = names[1];
}
else if (names.Length > 2)
{
modelRegister.FirstName = names[0];
modelRegister.LastName = listing.ContactName.Substring(listing.ContactName.IndexOf(" ") + 1);
}
// Register account
var resultRegister = await accountController.RegisterAccount(modelRegister);
// Add errors
AddErrors(resultRegister);
// Show errors if not succeed
if (!resultRegister.Succeeded)
{
var model = new ListingUpdateModel()
{
ListingItem = listing
};
// Populate model with listing
await PopulateListingUpdateModel(listing, model);
return View("ListingUpdate", model);
}
// update current user id
var user = await UserManager.FindByNameAsync(listing.ContactEmail);
userIdCurrent = user.Id;
}
bool updateCount = false;
int nextPictureOrderId = 0;
// Set default listing type ID
if (listing.ListingTypeID == 0)
{
var listingTypes = CacheHelper.ListingTypes.Where(x => x.CategoryListingTypes.Any(y => y.CategoryID == listing.CategoryID));
if (listingTypes == null)
{
TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
TempData[TempDataKeys.UserMessage] = "[[[There are not listing types available yet.]]]";
return RedirectToAction("Listing", new { id = listing.ID });
}
listing.ListingTypeID = listingTypes.FirstOrDefault().ID;
}
if (listing.ID == 0)
{
listing.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added;
listing.IP = Request.GetVisitorIP();
listing.Expiration = DateTime.MaxValue.AddDays(-1);
listing.UserID = userIdCurrent;
listing.Enabled = true;
listing.Currency = CacheHelper.Settings.Currency;
updateCount = true;
_listingService.Insert(listing);
}
else
{
if (await NotMeListing(listing.ID))
return new HttpUnauthorizedResult();
var listingExisting = await _listingService.FindAsync(listing.ID);
listingExisting.Title = listing.Title;
listingExisting.Description = listing.Description;
listingExisting.Tags = listing.Tags;
listingExisting.Active = listing.Active;
listingExisting.Price = listing.Price;
listingExisting.ContactEmail = listing.ContactEmail;
listingExisting.ContactName = listing.ContactName;
listingExisting.ContactPhone = listing.ContactPhone;
listingExisting.Latitude = listing.Latitude;
listingExisting.Longitude = listing.Longitude;
listingExisting.Location = listing.Location;
listingExisting.ShowPhone = listing.ShowPhone;
listingExisting.ShowEmail = listing.ShowEmail;
listingExisting.CategoryID = listing.CategoryID;
listingExisting.ListingTypeID = listing.ListingTypeID;
listingExisting.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;
_listingService.Update(listingExisting);
}
// Delete existing fields on item
var customFieldItemQuery = await _customFieldListingService.Query(x => x.ListingID == listing.ID).SelectAsync();
var customFieldIds = customFieldItemQuery.Select(x => x.ID).ToList();
foreach (var customFieldId in customFieldIds)
{
await _customFieldListingService.DeleteAsync(customFieldId);
}
// Get custom fields
var customFieldCategoryQuery = await _customFieldCategoryService.Query(x => x.CategoryID == listing.CategoryID).Include(x => x.MetaField.ListingMetas).SelectAsync();
var customFieldCategories = customFieldCategoryQuery.ToList();
foreach (var metaCategory in customFieldCategories)
{
var field = metaCategory.MetaField;
var controlType = (BeYourMarket.Model.Enum.Enum_MetaFieldControlType)field.ControlTypeID;
string controlId = string.Format("customfield_{0}_{1}_{2}", metaCategory.ID, metaCategory.CategoryID, metaCategory.FieldID);
var formValue = form[controlId];
if (string.IsNullOrEmpty(formValue))
continue;
formValue = formValue.ToString();
var itemMeta = new ListingMeta()
{
ListingID = listing.ID,
Value = formValue,
FieldID = field.ID,
ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added
};
_customFieldListingService.Insert(itemMeta);
}
await _unitOfWorkAsync.SaveChangesAsync();
if (Request.Files.Count > 0)
{
var itemPictureQuery = _listingPictureservice.Queryable().Where(x => x.ListingID == listing.ID);
if (itemPictureQuery.Count() > 0)
nextPictureOrderId = itemPictureQuery.Max(x => x.Ordering);
}
if (files != null && files.Count() > 0)
{
foreach (HttpPostedFileBase file in files)
{
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
// Picture picture and get id
var picture = new Picture();
picture.MimeType = "image/jpeg";
_pictureService.Insert(picture);
await _unitOfWorkAsync.SaveChangesAsync();
// Format is automatically detected though can be changed.
ISupportedImageFormat format = new JpegFormat { Quality = 90 };
Size size = new Size(500, 0);
//https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/
// Initialize the ImageFactory using the overload to preserve EXIF metadata.
using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
{
var path = Path.Combine(Server.MapPath("~/images/listing"), string.Format("{0}.{1}", picture.ID.ToString("00000000"), "jpg"));
// Load, resize, set the format and quality and save an image.
imageFactory.Load(file.InputStream)
.Resize(size)
.Format(format)
.Save(path);
}
var itemPicture = new ListingPicture();
itemPicture.ListingID = listing.ID;
itemPicture.PictureID = picture.ID;
itemPicture.Ordering = nextPictureOrderId;
_listingPictureservice.Insert(itemPicture);
nextPictureOrderId++;
}
}
}
await _unitOfWorkAsync.SaveChangesAsync();
// Update statistics count
if (updateCount)
{
_sqlDbService.UpdateCategoryItemCount(listing.CategoryID);
_dataCacheService.RemoveCachedItem(CacheKeys.Statistics);
}
TempData[TempDataKeys.UserMessage] = "[[[Listing is updated!]]]";
return RedirectToAction("Listing", new { id = listing.ID });
}
My page screenshot:
enter image description here
Consequently, i can insert location in my db. But, i can't latitude and longitude insert.
How can i solve this problem?
initmap function:
function initMap() {
var isDraggable = $(document).width() > 480 ? true : false; // If document (your website) is wider than 480px, isDraggable = true, else isDraggable = false
var mapOptions = {
draggable: isDraggable,
scrollwheel: false, // Prevent users to start zooming the map when scrolling down the page
zoom: 7,
center: new google.maps.LatLng(39.8688, 32.2195),
};
#{ var hasLatLng = #Model.ListingItem.Latitude.HasValue && #Model.ListingItem.Longitude.HasValue; }
var hasLatLng = #hasLatLng.ToString().ToLowerInvariant();
#if (hasLatLng){
<text>
mapOptions = {
center: new google.maps.LatLng(#Model.ListingItem.Latitude.Value.ToString(System.Globalization.CultureInfo.InvariantCulture), #Model.ListingItem.Longitude.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)),
zoom: 7
};
</text>
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
#if (hasLatLng){
<text>
var marker = new google.maps.Marker({
position: new google.maps.LatLng(#Model.ListingItem.Latitude, #Model.ListingItem.Longitude),
map: map
});
marker.setVisible(true);
</text>
}
geocoder = new google.maps.Geocoder();
var input = (document.getElementById('Location'));
// Try HTML5 geolocation
if (#Model.ListingItem.ID == 0){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
geocoder.geocode({ 'latLng': pos }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(14);
map.setCenter(pos);
marker = new google.maps.Marker({
position: pos,
map: map,
content: results[1].formatted_address
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
$('#Location').val(results[1].formatted_address);
$('#Latitude').val(pos.lat());
$('#Longitude').val(pos.lng());
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// Set lat/long
$('#Latitude').val(place.geometry.location.lat());
$('#Longitude').val(place.geometry.location.lng());
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(12);
}
marker.setIcon(({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
google.maps.event.addDomListener(input, 'keydown', function (e) {
if (e.keyCode == 13) {
if (e.preventDefault) {
e.preventDefault();
}
else {
// Since the google event handler framework does not handle
e.cancelBubble = true;
e.returnValue = false;
}
}
});
}
save button:
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button class="btn btn-primary" type="submit"><i class="fa fa-save"></i> [[[Save]]]</button>
<i class="fa fa-remove"></i> [[[Cancel]]]
</div>
</div>
I try to add a listener to my autocomplete box in order to select the first choice when pressing enter but it doesn't work.
event.addDomListener(input, 'keypress', (e) {
if (e.keyCode == 13) {
event.trigger(html.document.getElementById('pac-input').innerHtml, 'keydown',
html.KeyCode.DOWN);
}
});
I am not sure concerning
html.document.getElementById('pac-input').innerHtml
Thanks for your help.
[edit]
I use angular2.0.0-beta.21.
My template is :
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location">
<div id="map-canvas" style="height: 500px;"></div>
and my component :
#Component(
selector: 'myComponent',
templateUrl: 'template.html',
pipes: const [IntlPipe]
)
class MyComponent implements OnInit {
final UserService _userService;
final IntlService _intlService;
Autocomplete autocomplete;
GMap map;
String infoMessage = "";
String errorMessage = "";
CornersComponent(this._userService, this._intlService);
#override
ngOnInit() {
var mapOptions = new MapOptions()
..zoom = 13
..maxZoom = 19
..minZoom = 12
..center = new LatLng(48.871083, 2.346348)
..mapTypeId = MapTypeId.ROADMAP
..streetViewControl = false
..panControl = false
..mapTypeControl = false
..scrollwheel = false
..styles = <MapTypeStyle>[
new MapTypeStyle()
..featureType = MapTypeStyleFeatureType.POI_BUSINESS
..elementType = MapTypeStyleElementType.LABELS
..stylers = <MapTypeStyler>[
new MapTypeStyler()
..visibility = 'off'
]
];
map = new GMap(html.querySelector("#map-canvas"), mapOptions);
var input = html.document.getElementById('pac-input') as html
.InputElement;
map.controls[ControlPosition.TOP_LEFT].push(input);
autocomplete = new Autocomplete(input);
autocomplete.bindTo('bounds', map);
final infowindow = new InfoWindow();
final marker = new Marker(new MarkerOptions()
..map = map
..anchorPoint = new Point(0, -29));
autocomplete.onPlaceChanged.listen((_) {
infowindow.close();
marker.visible = false;
final place = autocomplete.place;
if (place.geometry == null) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport != null) {
map.fitBounds(place.geometry.viewport);
} else {
map.center = place.geometry.location;
map.zoom = 15; // Why 17? Because it looks good.
}
marker.icon = new Icon()
..url = place.icon
..size = new Size(71, 71)
..origin = new Point(0, 0)
..anchor = new Point(17, 34)
..scaledSize = new Size(35, 35);
marker.position = place.geometry.location;
marker.visible = true;
String address = '';
if (place.addressComponents != null) {
address = [
(place.addressComponents[0] != null &&
place.addressComponents[0].shortName != null
? place.addressComponents[0].shortName
: ''),
(place.addressComponents[1] != null &&
place.addressComponents[1].shortName != null
? place.addressComponents[1].shortName
: ''),
(place.addressComponents[2] != null &&
place.addressComponents[2].shortName != null
? place.addressComponents[2].shortName
: '')
].join(' ');
}
infowindow.content = '<div><strong>${place.name}</strong><br>${address}';
infowindow.open(map, marker);
});
event.addDomListener(input, 'keypress', (e) {
assert(e is html.KeyboardEvent);
if (e.keyCode == html.KeyCode.ENTER) {
event.trigger(input, 'keydown',
new html.KeyEvent('keydown', keyCode: html.KeyCode.DOWN));
}
});
}
}
I have found a workaround :
Calling at the end on the ngOnInit method :
context.callMethod('myJavascriptMethod');
function myJavascriptMethod() {
var input = document.getElementById('pac-input');
google.maps.event.addDomListener(input, 'keypress', function (e) {
if (e.keyCode === 13) {
google.maps.event.trigger(this, 'keydown', {"keyCode": 40});
}
});
}
The following code should work:
import 'dart:js_util' show jsify;
event.addDomListener(input, 'keypress', (e) {
assert(e is html.KeyboardEvent);
if (e.keyCode == html.KeyCode.ENTER) {
event.trigger(input, 'keydown', jsify({'keyCode': html.KeyCode.DOWN}));
}
});
You can alternatively use the following to trigger events:
input.dispatchEvent(new html.KeyEvent('keydown', keyCode: html.KeyCode.DOWN));
Background:
I have a Parse database of images. Simply, my code does this:
A user, through a Parse Cloud call requests an image ("getNewPicture"). Nested within I check if he has seen any pictures before (alongside other requirements) and if so deliver one specific picture (getSpecifiedPicture). If he has not, then I deliver a new picture (getNewPicture).
Issue:
Calling "getNewPicture" through Parse Cloud Code function I get an error code 141. What's strange is that it works through Android but not iOS.
My code:
Parse.Cloud.define("getNewPicture", function(request, response) {
var SeenPictures = Parse.Object.extend("SeenPictures");
var query = new Parse.Query(SeenPictures);
var username = request.params.username;
var notWantedPics = [];
query.ascending("createdAt");
query.equalTo("username", username);
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
if (results[i].get("likes") == 1 || results[i].get("dislikes") == 1) {
notWantedPics.push(results[i].get("pictureId"));
results.splice(i, 1);
i--;
}
}
if (results != 0) {
getSpecifiedPicture(results[0].get("pictureId"), {
success: function(returnValue) {
response.success(returnValue);
},
error: function(error) {
response.error(error);
}
});
} else {
getNewPicture(username, notWantedPics, {
success: function(returnValue) {
response.success(returnValue);
},
error: function(error) {
response.error(error);
}
});
}
},
error: function() {
response.error(error);
}
});
});
function getSpecifiedPicture(specifiedPic, callback) {
var Pictures = Parse.Object.extend("Pictures");
var pictures = new Parse.Query(Pictures);
pictures.get(specifiedPic, {
success: function(picture) {
callback.success(picture);
},
error: function(error) {
callback.error(error);
}
});
}
function getNewPicture(username, notWantedPics, callback) {
var Pictures = Parse.Object.extend("Pictures");
var pictures = new Parse.Query(Pictures);
pictures.notEqualTo("photographerUserName", username);
pictures.notContainedIn("objectId", notWantedPics);
pictures.ascending("createdAt");
pictures.find({
success: function(results) {
if (results.length > 0) {
var object = results[0];
//Some other fancy stuff
object.save();
callback.success(object);
}
},
error: function(error) {
callback.error(error);
}
});
}
Why am I getting code 141? Any help is appreciated.
Thanks.
Your callbacks are a mess. I rewrote it to follow more of a promise chain style. Much easier to follow. Also, underscore.js is your friend. Hopefully I got your idea right.
var _ = require('underscore'); // Javascript Library
Parse.Cloud.define("getNewPicture", function(request, response) {
var username = request.params.username;
var notWantedPics = [];
if (!username) {
return response.error('No username.');
}
var query1 = new Parse.Query("SeenPictures");
query1.ascending("createdAt");
query1.equalTo("username", username);
var SeenPictures = query1.find();
return Parse.Promise.when([SeenPictures]).then(function (SeenPictures) {
SeenPictures = _.filter(SeenPictures, function (SeenPicture) {
if (SeenPicture.get("likes") == 1 || SeenPicture.get("dislikes") == 1) {
notWantedPics.push(SeenPicture.get("pictureId"));
return false;
}
else {
return true;
}
});
// notWantedPics?
if (SeenPictures > 0) {
var query2 = new Parse.Query("Pictures");
var Pictures = [query2.get(SeenPictures[0].get('pictureId'))];
}
else {
var query2 = new Parse.Query("Pictures");
query2.notEqualTo("photographerUserName", username);
query2.notContainedIn("objectId", notWantedPics);
query2.ascending("createdAt");
var Pictures = query2.find();
}
return Parse.Promise.when([Pictures]);
}).then(function (Pictures) {
if (Pictures > 0) {
// Success
return response.success(Pictures[0]);
} else {
return Parse.Promise.error("No pictures.");
}
}, function (error) {
// Error
return response.error(error);
});
});
I'm trying to get the name of a location from given latitude and longitude.
Is there any possibility to get it like
getNameOfLocation(longitude,latitude)?
For example getNameOfLocation(48.1471904942317, 11.591434478759765) --> results Munich
I don't want to use any graphical elements to show like Google Maps.
Any ideas?
Thanks for help
var geo = Ext.create('Ext.util.Geolocation', {
autoUpdate: false,
listeners: {
locationupdate: function(geo) {
alert('New latitude: ' + geo.getLatitude());
},
locationerror: function(geo, bTimeout, bPermissionDenied, bLocationUnavailable, message) {
if(bTimeout){
alert('Timeout occurred.');
} else {
alert('Error occurred.');
}
}
}
});
geo.updateLocation();
try this..
function getNameOfLocation(lat, lng) {
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert(results[0].formatted_address) // your result
//country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
city= results[0].address_components[i];
break;
}
}
}
} else {
alert("No result");
}
} else {
alert("failed: " + status);
}
});
}
You can send an Ajax request to google maps API. For Example:
http://maps.googleapis.com/maps/api/geocode/json?latlng=48.1471904942317,11.591434478759765&sensor=false
and then parse the JSON result.