需要从谷歌地图获得当前的经纬度
问题描述:
我有下面的代码,它从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火:
$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的谷歌地图,它显示LAT和LONG,但在地图上移动他们不改变。
任何人都可以帮忙吗?
答
你要听如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
});
我试图添加代码如下:\t $(文件)。就绪(函数(){ \t \t initialiseGoogleMaps( $( '#谷歌地图 - ')); \t \t \t变种地图= '#谷歌地图 -'; \t \t \t google.maps.event.addListener(地图, 'center_changed的',函数(){ \t \t VAR中心= map.getCenter(); \t \t \t \t \t的console.log(中心); \t \t \t}); \t});但我得到的错误:TypeError:c是未定义的? –
2014-10-28 12:09:41
那是什么? 'var map ='#google-map - 请提供您的代码**输出**(由您的PHP打印的内容)。该行通常应为:'VAR地图=新google.maps.map(元件,的MapOptions);' – MrUpsidown 2014-10-28 12:13:42