我正在开发一个mvc5 Web应用程序。我正在尝试将用户的位置(纬度,经度)存储到数据库中。我可以保存位置名称。但是,我无法保存纬度和经度信息。我该如何插入这些?
感谢您的帮助。
listing.Cshtml文件:
<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 });
}
我的页面截图:
因此,我可以在我的数据库中插入位置。但是,我不能插入纬度和经度。
我该如何解决这个问题?
initmap功能:
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;
}
}
});
}
保存按钮:
<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>
<a href="@Url.Action("Listings", "Listing")" class="btn btn-default"><i class="fa fa-remove"></i> [[[Cancel]]]</a>
</div>
</div>