我正在尝试使用谷歌自动填充地点和流量图层地图。 我使用api密钥包含 libraries = places 和 callback = initMap ,但自动填充功能不起作用。如果我删除了callback = initMap,那么自动完成工作正在运行,但是使用callback = initMap自动完成功能不起作用,只显示流量层映射。提前谢谢。
<style>
#map {
height: 500px;
}
</style>
<form action="" method="post">
<input type="text" name="location" onFocus="initialize()" id="autocomplete">
<input type="submit" name="submit" >
</form>
<div id="map"></div><!--Traffic Map-->
<?php
$lat = '';
$long = '';
if(isset($_POST['submit']))
{
$address = urlencode($_POST['location']);
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$address";
$geocode = file_get_contents($url);
$output = json_decode($geocode);
if ($output->status == "OK")
{
$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;
}
else{
echo $output->status;
}
}
?>
<script><!--AutoComplete-->
var autocomplete;
function initialize() {
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),
{ types: ['geocode'] });
google.maps.event.addListener(autocomplete, 'place_changed', function() {
});
}
</script>
<script><!--TrafficLayer-->
function initMap()
{
var mapOptions = {
center: new google.maps.LatLng(<?php echo $lat; ?>, <?php echo $long; ?>),
zoom: 12,
scrollwheel: true,
draggable: true,
panControl: true,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true,
rotateControl: true,
};
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
var marker = new google.maps.Marker({
position:{lat: <?php echo $lat; ?>, lng: <?php echo $long; ?>},
map:map,
animation: google.maps.Animation.DROP,
});
}
</script>
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<!--<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>-->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places&callback=initMap"></script>
答案 0 :(得分:0)
在构建地图后,您是否可以尝试将代码(用于自动完成目的)放在initMap()中。
有点像这样:
var autocomplete;
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),
{ types: ['geocode'] });
google.maps.event.addListener(autocomplete, 'place_changed', function() {
});
宣布后
var marker = new google.maps.Marker({
position:{lat: <?php echo $lat; ?>, lng: <?php echo $long; ?>},
map:map,
animation: google.maps.Animation.DROP,
});