首页 文章

如何使用谷歌自动填充和谷歌流量图层 Map api [重复]

提问于
浏览
-1

这个问题在这里已有答案:

我正在尝试使用谷歌自动填充地点和流量图层 Map . 我使用api密钥包含 libraries=placescallback=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>

1 回答

  • 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,
    });
    

相关问题