Kamis, 28 Maret 2013

Membuat Polygon pada Google Map v3 dengan Window Popup Event OnClick

Sebenarnya kode program ini adalah tutorial dari dokumentasi resmi Google Maps v3. Tetapi karena sangat pentingnya untuk Penulis karena pekerjaan tertentu maka Penulis postingkan disini. Kode program Javascript ini menggunakan Google Map v3 untuk menampilkan Polygon dan memberi fasilitas klik dan menampilkan Window Popup jika polygon tersebut diklik.

Kode programnya di bawah ini, siap dicopy paste di halaman web. Seharusnya langsung bisa dijalankan :


<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false"></script>
    <script>

      var map;
      var infoWindow;

      function initialize2() {
        var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);
        var mapOptions = {
          zoom: 5,
          center: myLatLng,
          mapTypeId: google.maps.MapTypeId.TERRAIN
        };

        var bermudaTriangle;

        map = new google.maps.Map(document.getElementById('map-canvas'),
            mapOptions);

        var triangleCoords = [
            new google.maps.LatLng(25.774252, -80.190262),
            new google.maps.LatLng(18.466465, -66.118292),
            new google.maps.LatLng(32.321384, -64.75737)
        ];



        bermudaTriangle = new google.maps.Polygon({
          paths: triangleCoords,
          strokeColor: '#FF0000',
          strokeOpacity: 0.8,
          strokeWeight: 3,
          fillColor: '#FF0000',
          fillOpacity: 0.35
        });

        bermudaTriangle.setMap(map);

        // Add a listener for the click event
        google.maps.event.addListener(bermudaTriangle, 'click', showArrays);

        infowindow = new google.maps.InfoWindow();
      }

      function showArrays(event) {

        // Since this Polygon only has one path, we can call getPath()
        // to return the MVCArray of LatLngs
        var vertices = this.getPath();

        var contentString = '<b>Bermuda Triangle Polygon</b><br>';
        contentString += 'Clicked Location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() + '<br>';

        // Iterate over the vertices.
        for (var i =0; i < vertices.length; i++) {
          var xy = vertices.getAt(i);
          contentString += '<br>' + 'Coordinate: ' + i + '<br>' + xy.lat() +',' + xy.lng();
        }

        // Replace our Info Window's content and position
        infowindow.setContent(contentString);
        infowindow.setPosition(event.latLng);

        infowindow.open(map);
      }
      
      google.maps.event.addDomListener(window, 'load', initialize2);
    </script>
    <br />
<div id="map-canvas" style="height: 500px; width: 500px;">
</div>


Hasilnya :



Semoga Bermanfaat.