我有以下代码,它使用PHP中的地址变量创建Google地图。
使用Javascript:
function initialiseGoogleMaps(selector) {
geocoder = null;
maps = [];
bounds = [];
if (!selector) {
selector = '.googleMap';
}
$.each($(selector), function(index, value) {
var $this = $(value),
mapOptions = $this.data(),
addresses = $this.data('addresses') + '';
addresses = addresses ? addresses.split(',') : [];
$this.attr('id', 'google-map-' + index);
maps[index] = new google.maps.Map(this, mapOptions);
bounds[index] = new google.maps.LatLngBounds();
for (var i=0; i < addresses.length; i++) {
if (addresses[i] === '') {
continue;
}
initialiseGoogleGeocoder().geocode({'address': addresses[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
placeMarker(maps[index], bounds[index], results[0].geometry.location, addresses[i]);
}
});
}
});
}
function placeMarker(map, bounds, location, text) {
var marker = new google.maps.Marker({
map: map,
position: location,
title: text
});
bounds.extend(marker.position);
map.fitBounds(bounds);
var zoom = map.getZoom();
map.setZoom(zoom > 6 ? 6 : zoom);
}
function initialiseGoogleGeocoder() {
if (geocoder === null) {
geocoder = new google.maps.Geocoder();
}
return geocoder;
}
PHP / HTML和Javascript fire:
$distinctPostcodes = array_filter(array_unique(Hash::extract($addresses, '{n}.Address.postcode')));
if (!empty($distinctPostcodes)) {
echo $this->Html->tag('div', '', array(
'class' => 'googleMap',
'id' => 'google-map-' . $uuid,
'data-addresses' => implode(',', $distinctPostcodes),
'data-zoom' => 5,
)),
$this->Html->link('Fix Map', array(
'controller' => 'addresses',
'action' => 'fixmap', $address['company_id'],
));
}
<script type="text/javascript">
$(document).ready(function() {
initialiseGoogleMaps($('#google-map-<?php echo $uuid; ?>'));
});
</script>
我需要做的是,当用户将地图移动到不同的位置时,我需要从DOM获取经度和经度并通过POST请求将其保存到mySQL中。
我在DOM中查看了Google地图,它显示了LAT和LONG,但移动地图后它们不会改变。
有人可以帮忙吗?
答案 0 :(得分:1)
您需要收听地图事件,例如bounds_changed
,center_changed
或dragend
(取决于您的确切需要),获取地图中心坐标(如果这是您想要的) ),并将其传递给你的后端,最有可能是在AJAX请求的帮助下。
此处提供的地图活动:https://developers.google.com/maps/documentation/javascript/reference#Map
例如:
google.maps.event.addListener(map, 'center_changed', function() {
var center = map.getCenter();
// AJAX request to your backend with the 'center' variable
});