如何通过点击谷歌地图获取坐标

时间:2011-07-06 09:31:13

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

我是谷歌地图的新手,想要使用谷歌地图的JavaScript API来显示房屋作为标记。我希望一个人能够在地图上点击以放置标记,可以再次单击该标记以将其移除或拖动到地图上的其他位置。然后,我希望脚本获得cordinates(lat和long),以便我可以将它添加到数据库表中。知道我应该怎么做吗?我在codeIgniter中使用PHP。

2 个答案:

答案 0 :(得分:0)

一个好的起点是查看参考手册:http://code.google.com/apis/maps/documentation/javascript/reference.html

如果你看那里的地图,你会发现它有一个叫做“点击”的事件。你做的是在你的地图初始化之后你制作了一个eventlistener,它会监听click事件。发生这种情况时,然后在该位置放置一个标记,如果要删除它,则在该标记上为click事件添加一个eventlistener,如果要拖动它,则将其设置为可拖动。

如果您想再次使用他们所持有的信息,请记住将您的标记存储在数组中。

我希望这会有所帮助。

答案 1 :(得分:0)

我迟到了。请在下面找到代码snipet。



/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

<div id="map"></div>
    <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
        });
        var marker;
        map.addListener('click', function(e) {
          
          if(marker){

            var latlng = new google.maps.LatLng(e.latLng.lat(), e.latLng.lng());
            marker.setPosition(latlng);
          }else{
            marker = new google.maps.Marker({
                  position: {lat : e.latLng.lat(), lng : e.latLng.lng()},
                  map: map
                })
          }

          alert("lat : "+e.latLng.lat()+ "; lng : "+e.latLng.lng())

          });
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDNPpCPQOwkMotaDj0IgHQ7HDAE8cz6-4U&callback=initMap"
    async defer></script>
&#13;
&#13;
&#13;

相关问题