如何在谷歌地图中指定位置?

时间:2017-05-25 10:12:01

标签: javascript php google-maps google-maps-api-3

我想在谷歌地图中指定位置,我有javascript代码工作正常,但我知道如何从php变量指定位置 以下是示例代码。

<html>
<head>
<title></title>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCqgya6hvq6zu3Z2xeT5xEGPPi5pY2ize4&callback=initMap"></script>
</head>
<body>

<?php
//I want to search this location in google map
$location="Kigali Rwanda";
?>

<script>
    var myMap;
    var myLatlng = new google.maps.LatLng(52.518903284520796,-1.450427753967233);
    function initialize() {
        var mapOptions = {
            zoom: 13,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP  ,
            scrollwheel: false
        }
        myMap = new google.maps.Map(document.getElementById('map'), mapOptions);
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: myMap,
            title: 'Name Of Business',
            icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png'
        });
    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

<div id="map" style="width:500px; height: 500px;">

</div>


</body>
</html>

请有人帮助我

2 个答案:

答案 0 :(得分:1)

在这种情况下,您可以使用Geocoding service

function initMap() {

  //var address = '<?php echo $location ?>';
  var address = 'Kigali Rwanda';

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8
  });

  var geocoder = new google.maps.Geocoder();

  geocoder.geocode({
      'address': address
    },
    function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        new google.maps.Marker({
          position: results[0].geometry.location,
          map: map
        });
        map.setCenter(results[0].geometry.location);
      }
    });
}
#map {
  height: 400px;
  width: 100%;
}
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>

答案 1 :(得分:0)

你必须使用lat,lng来指定位置。如果是国家或州名称,您应该获取位置的lat,lng并在代码中定义它。在隐藏的输入字段中插入php变量的值。在运行脚本时获取值并处理它。