我正在尝试使用以下代码在网页中使用Google MAP API。
网页有两个字段地址,地理位置字段。 输入地址,更改事件将更新地图 与地址。标记将放置在地址处。 如果用户需要移动标记,他们可以和地理位置 字段将自动更新。
然后我得到此错误,当我运行此代码时:
Uncaught TypeError: Cannot read property 'x' of undefined at Av (common.js:150)
以下是Javascript代码:
function googleMapAdmin() {
var geocoder = new google.maps.Geocoder();
var map;
var marker;
var self = {
initialize: function() {
var lat = 0;
var lng = 0;
var zoom = 2;
// set up initial map to be world view. also, add change
// event so changing address will update the map
existinglocation = self.getExistingLocation();
if (existinglocation) {
lat = existinglocation[0];
lng = existinglocation[1];
zoom = 18;
}
var latlng = new google.maps.LatLng(lat,lng);
var myOptions = {
zoom: zoom,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (existinglocation) {
self.setMarker(latlng);
}
$("#id_address").change(function() {self.codeAddress();});
},
getExistingLocation: function() {
var geolocation = $("#id_geolocation").val();
if (geolocation) {
return geolocation.split(',');
}
},
codeAddress: function() {
var address = $("#id_address").val();
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latlng = results[0].geometry.location;
map.setCenter(latlng);
map.setZoom(18);
self.setMarker(latlng);
self.updateGeolocation(latlng);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
},
setMarker: function(latlng) {
if (marker) {
self.updateMarker(latlng);
} else {
self.addMarker({'latlng': latlng, 'draggable': true});
}
},
addMarker: function(Options) {
marker = new google.maps.Marker({
map: map,
position: Options.latlng
});
var draggable = Options.draggable || false;
if (draggable) {
self.addMarkerDrag(marker);
}
},
addMarkerDrag: function() {
marker.setDraggable(true);
google.maps.event.addListener(marker, 'dragend', function(new_location) {
self.updateGeolocation(new_location.latLng);
});
},
updateMarker: function(latlng) {
marker.setPosition(latlng);
},
updateGeolocation: function(latlng) {
$("#id_geolocation")
.val(latlng.lat() + "," + latlng.lng())
.trigger('change');
}
}
return self;
}
以下是HTML代码:
<div class="form-row field-middle_name" style="padding-bottom: 28px; margin-bottom: 10px;">
<div>
<label for="id_middle_name">Search Address:</label>
<div class="row">
<div class="col-md-3">
<input type="text" class="form-control" name="address" id="id_address" >
</div>
</div>
</div>
<div class="map_canvas_wrapper">
<div id="map_canvas"></div>
</div>
<div class="form-row field-middle_name">
<div>
<label for="id_middle_name">Geolocation:</label>
<div class="row">
<div class="col-md-3">
<input type="text" class="form-control" name="geolocation" id="id_geolocation">
</div>
</div>
</div>
这是CSS代码:
<style media="screen" type="text/css">
#id_address {width: 40em;}
.map_canvas_wrapper {margin-left: 106px;}
#map_canvas {width: 100%; height: 40em;}
</style>