1.自動加載文本框的坐標,並在地圖標注點。
2.點擊地圖時,並且“逆地理編碼”解析出地址方在文本框
js
- var lnglatXY;
- var marker;
- //初始化地圖對象,加載地圖
- var map = new AMap.Map('mapContainer', {
- resizeEnable: true,
- view: new AMap.View2D({
- center: new AMap.LngLat(106.461983, 29.516409),
- zoom: 10,
- })
- });
- //加點
- marker = new AMap.Marker({
- icon: "http://webapi.amap.com/images/marker_sprite.png",
- position: new AMap.LngLat($("#EditFormMap input[name='longitude']").val(), $("#EditFormMap input[name='latitude']").val())
- });
- //uncaught exception: Invalid Object: Pixel(NaN, NaN)
- //這里報這個錯誤,是因為不能讀取到$("#EditFormMap input[name='longitude']").val(), $("#EditFormMap input[name='latitude']").val() 的值
- //因為要在本頁點【地圖】按鈕,才會賦值。所以該注銷掉
- //marker.setMap(map); //在地圖上添加點
- AMap.event.addListener(map, 'click', getLnglat);
- //鼠標在地圖上點擊,獲取經緯度坐標
- function getLnglat(e) {
- map.clearMap(); //刪除地圖上的所有覆蓋物
- //經度賦值
- document.getElementsByName('longitude').value = e.lnglat.getLng();
- $("#EditFormMap input[name='longitude']").attr("value", e.lnglat.getLng())
- //緯度賦值
- document.getElementsByName('latitude').value = e.lnglat.getLat();
- $("#EditFormMap input[name='latitude']").attr("value", e.lnglat.getLat());
- //逆地址編碼需要的 X,Y
- lnglatXY = new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat());
- geocoder();
- }
- function geocoder() {
- var MGeocoder;
- //加載地理編碼插件
- map.plugin(["AMap.Geocoder"], function () {
- MGeocoder = new AMap.Geocoder({
- radius: 1000,
- extensions: "all"
- });
- //返回地理編碼結果
- AMap.event.addListener(MGeocoder, "complete", geocoder_CallBack);
- //逆地理編碼
- MGeocoder.getAddress(lnglatXY);
- });
- //加點
- marker = new AMap.Marker({
- icon: "http://webapi.amap.com/images/marker_sprite.png",
- position: lnglatXY,
- });
- marker.setMap(map); //在地圖上添加點
- //map.setFitView(); //縮放平移地圖到合適的視野級別,
- }
- //回調函數
- function geocoder_CallBack(data) {
- var address;
- //返回地址描述
- address = data.regeocode.formattedAddress;
- //console.info($("#EditFormMap input[name='address']"))
- //返回結果賦值(地址欄)
- //$("#EditFormMap input[name='address']").attr("value", address);
- $("#EditFormMap input[name='address']").attr("value", address);
- }
html
- <tr>
- <th align="right">經度:</th>
- <td>
- <input id="longitude" name="longitude" class="easyui-validatebox" data-options="required:true">
- <font color="red">*.(經緯度直接鼠標在地圖選取)</font>
- </td>
- </tr>
- <tr>
- <th align="right">緯度:</th>
- <td>
- <input id="latitude" name="latitude" class="easyui-validatebox" data-options="required:true">
- <font color="red"></font>
- </td>
- </tr>
- <tr>
- <th align="right">地址:</th>
- <td>
- <input id="address" name="address" class="easyui-validatebox" style="width: 300px" data-options="required:true,validType:'maxlength[21]'">
- </td>
- </tr>
問題一:
狀況1.點擊地圖,光改變文本框的值,地圖上不加載圖標
狀況2.經常出現“AMap.Geocoder is not a constructor”
原因:
多次加載,easyui的原因。去掉就可以了。