Address Editor for ASP.NET MVC3 – Format the Address String by Google Map

image
輸入地址
image
自動查詢 google map 顯示查詢結果,將地址字串轉為 api 回應的結果

[Required]
[Display(Name = "地址")]
[UIHint("MvcAddressEditor")]
public string Address { get; set; }

利用 UIHint 自動套入 Template,另外新增一個 MvcAddressEditor.cshtml

@model String
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
$(function () {
var geocoder;
var map;
$(document).ready(function () {
geocoder = new google.maps.Geocoder();
//default location
//可以新增查詢當地位置當成預設值
//http://code.google.com/intl/zh-TW/apis/maps/documentation/javascript/basics.html
var latlng = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
//first show map
map = new google.maps.Map($("#" + "@(Html.ClientIdFor(p => p) + "-google-map-display")")[0], myOptions);
});

$("#" + "@(Html.ClientIdFor(p => p))").live("change", function () {
var address = $(this).val();
geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0].types[0] != "street_address") {
//the result address type
//alert("Please enter more detailed");
}
map.setCenter(results[0].geometry.location);
$("#"+"@(Html.ClientIdFor(p => p))").val(results[0].formatted_address);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
});
</script>
@Html.TextBoxFor(it => Model, new { Style = "width: 500px;" })
<div id='@(Html.ClientIdFor(p => p) + "-google-map-display")' style="width: 300px; height: 300px">
</div>

可以從這裡下載 Download 用的是 Google Maps Javascript API 第 3 版

Reference

Google Maps Javascript API 第 3 版服務

ClientIdFor Mvc Helper

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *