Tag Archive google

google maps: HTML5.Geolocation

คุณสมบัติใหม่ของ html5 คือ Geolocation API ช่วยให้ browser สามารถส่งตำแหน่งของตัวมันเองกลับไปให้ server ได้โดยใช้ตำแหน่ง gps หรือจากหมายเลข ip

แต่เพราะมันกระทบถึงความเป็นส่วนตัว ในการเขียนจึงต้องเผื่อว่า user ไม่อนุญาตให้ส่งตำแหน่งของตัวเองกลับมาไว้ด้วย ในตัวอย่างใช้

/* get position from HTML5 Geolocation */
function getGeolocation() {
    var position = false;
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(successCallback, errorCallback) {

            position = successCallback.coords;

            document.getElementById('latitudeA').innerHTML = successCallback.coords.latitude;
            document.getElementById('longitudeA').innerHTML = successCallback.coords.longitude;

        }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        /*Browser doesn't support Geolocation*/
        handleLocationError(false, infoWindow, map.getCenter());

        return false;
    }

    return position;
}

ส่ง position กลับมา ให้

function initMap(defaultLatitude = 13.7651991, defaultLongitude = 100.5368694) {
    position = getGeolocation();

    if (position == false || position == null || position === undefined || position.length <= 0 || typeof position == 'undefined') {
        position = {
            "latitude": defaultLatitude,
            "longitude": defaultLongitude,
        };
    }

    createMap('mapA', position);
}

แต่ถ้าหากไม่มีพิกัดส่งมา จะนำค่า default มาแสดงแทน

คุณสามารถดูตัวอย่างได้จาก google maps: HTML5.Geolocation หรือลองสร้างไฟล์ตามตัวอย่าง

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps APIs > Maps JavaScript API > HTML5 Geolocation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
  <div class="row">
    <div class="col-md-2">
      <h3>HTML5 Geolocation</h3>
      <dl>
        <dt>latitude</dt>
        <dd id="latitudeA"></dd>
        <dt>longitude</dt>
        <dd id="longitudeA"></dd>
      </dl>
    </div>
    <div class="col-md-10 map" id="mapA"></div>
  </div>
</div>
<script>
var infoWindow;
var map;
var position = false;

/* function createMaps */
function createMap(mapArea, position) {
    var latlng = new google.maps.LatLng(parseFloat(position.latitude), parseFloat(position.longitude));
    var infoWindow = new google.maps.InfoWindow;
    var map = new google.maps.Map(document.getElementById(mapArea), {
        "zoom": 18
    });

    map.setCenter(latlng);

    var marker = new google.maps.Marker({
        "map": map,
        "position": latlng,
    });

    infoWindow.open(map, marker);
    infoWindow.setContent('Latitude = ' + position.latitude + ', ' + ' longitude = ' + position.longitude);
    infoWindow.setPosition(latlng);
}

/* get position from HTML5 Geolocation */
function getGeolocation() {
    var position = false;
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(successCallback, errorCallback) {

            position = successCallback.coords;

            document.getElementById('latitudeA').innerHTML = successCallback.coords.latitude;
            document.getElementById('longitudeA').innerHTML = successCallback.coords.longitude;

        }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        /*Browser doesn't support Geolocation*/
        handleLocationError(false, infoWindow, map.getCenter());

        return false;
    }

    return position;
}

/* show error of HTML5 Geolocation */
function handleLocationError(browserHasGeolocation, infoWindow, position) {
    infoWindow.setPosition(position);
    infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
    infoWindow.open(map);
}

function initMap(defaultLatitude = 13.7651991, defaultLongitude = 100.5368694) {
    position = getGeolocation();

    if (position == false || position == null || position === undefined || position.length <= 0 || typeof position == 'undefined') {
        position = {
            "latitude": defaultLatitude,
            "longitude": defaultLongitude,
        };
    }

    createMap('mapA', position);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyDE5zb4r9sbN5S_GcD3NZRED1Ma3FzFqso"></script>
</body>
</html>

google maps: basic

พื้นฐานการสร้าง google maps จาก Maps JavaScript API

  1. เริ่มจาก ขอ Google API key ก่อน
  2. จากนั้นลองสร้าง code ง่ายๆ ตามตัวอย่าง
    .map {
    	border: #c00000 solid thin;
    	height: 100%;
    	min-height: 500px;
    }

    ส่วนนี้จะเป็น css class ที่ทำให้แน่ใจว่า พื้นที่แสดงแผนที่เห็นสูงอย่างน้อย 500 px เพราะว่าตัว google maps จะเอาความสูงของ div เอาไปใช้ ถ้าไม่กำหนดไว้ถึงสร้างแผนที่ได้ก็อาจจะมองไม่เห็น

  3. สร้างพื้นที่ไว้แสดงแผนที่ กำหนดให้ id=”mapA”
    <div class="map" id="mapA"></div>
  4. สร้างแผนที่
    /* function createMaps */
    function createMap(mapArea, position) {
        var latlng = new google.maps.LatLng(parseFloat(position.latitude), parseFloat(position.longitude));
        var infoWindow = new google.maps.InfoWindow;
        var map = new google.maps.Map(document.getElementById(mapArea), {
            "zoom": 8
        });
    
        map.setCenter(latlng);
    
        var marker = new google.maps.Marker({
            "map": map,
            "position": latlng,
        });
    
        infoWindow.open(map, marker);
        infoWindow.setContent('Latitude = ' + position.latitude + ', ' + ' longitude = ' + position.longitude);
        infoWindow.setPosition(latlng);
    }
    
    function initMap(defaultLatitude = 13.7651991, defaultLongitude = 100.5368694) {
        position = {
            "latitude": defaultLatitude,
            "longitude": defaultLongitude,
        };
    
        createMap('mapA', position);
    }
  5. โหลด Google Maps APIs โดยใช้
    <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=YOUR_API_KEY"></script>

    แทนที่ YOUR_API_KEY เป็น key ของเราเอง โดย callback= ตามด้วย function ที่ใช้สร้างแผนที่ หรือ function อื่นๆ ที่จะให้ทำงานหลังโหลดเพจเสร็จ ตามตัวอย่างคือ function initMap จะไม่สร้างแผนที่โดยตรงแต่จะใช้ function createMap สร้างให้อีกที ถ้าต้องการสร้างแผนที่เพิ่ม แค่เรียกใช้

    createMap('พื้นที่แสดงแผนที่', {
        "latitude": ค่า latitude,
        "longitude": ค่า longitude,
    });

    ก็จะมีแผนที่ที่มีหน้าตาคล้ายๆอีกอันเพิ่มขึ้นมา

ดูตัวอย่างได้ที่ google maps: basic หรือจะลองสร้างไฟล์เอง

@charset "utf-8";
/* CSS Document */
.map {
	border: #c00000 solid thin;
	height: 100%;
	min-height: 500px;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps APIs > Maps JavaScript API > Simple Map</title>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="map" id="mapA"></div>
<script>
/* function createMaps */
function createMap(mapArea, position) {
    var latlng = new google.maps.LatLng(parseFloat(position.latitude), parseFloat(position.longitude));
    var infoWindow = new google.maps.InfoWindow;
    var map = new google.maps.Map(document.getElementById(mapArea), {
        "zoom": 8
    });

    map.setCenter(latlng);

    var marker = new google.maps.Marker({
        "map": map,
        "position": latlng,
    });

    infoWindow.open(map, marker);
    infoWindow.setContent('Latitude = ' + position.latitude + ', ' + ' longitude = ' + position.longitude);
    infoWindow.setPosition(latlng);
}

function initMap(defaultLatitude = 13.7651991, defaultLongitude = 100.5368694) {
    position = {
        "latitude": defaultLatitude,
        "longitude": defaultLongitude,
    };

    createMap('mapA', position);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyDE5zb4r9sbN5S_GcD3NZRED1Ma3FzFqso"></script>
</body>
</html>

การกำหนด function ให้ทำงานหลังโหลดเพจเสร็จนอกจากใช้ตัวแปร callback แล้วยังสามารถใช้

google.maps.event.addDomListener(window, 'load', initMap);

ได้เหมือนกัน

อ่านเพิ่มเติม

google maps จาก jQuery ajax

ใช้เจคิวรี่เอแจ็กซ์ โหลด fragment google map เข้ามาแสดงในเท็ปแล้วไม่ขึ้น ไม่เห็น ทั้งๆที่ก็เขียน code ตามปกติ ดูตรงๆ ไม่ผ่านเอเจ็กซ์ ก็ทำงานปกติ ให้เปลี่ยนมาใช้ HTML fragment code ตามนี้ครับ

<div id="map-canvas" style="width: 100$; height: 400px"></div>
<script type="text/javascript">
function initialize()
{
	var mapOptions = {
		center: {lat: 13.799604, lng: 100.51129},
		zoom: 16
	};
	var map = new google.maps.Map(document.getElementById('map-canvas'),
		mapOptions);
}

$(function()
{
	$.getScript("https://maps.googleapis.com/maps/api/js?key=ใส่ google map API key ตรงนี้&async=2&callback=initialize", function () {});
});
</script>

Remove babylon search ใน Firefox

อยู่ๆก็มีเจ้าbabylon มาแทน Google หาอะไรก็ไม่ค่อยเจอ อยากให้กลับไปเป็นพี่เกิ้นเหมือนเดิม ทำตามนี่ครับ

  1. พิมพ์ about:config ในช่องที่ไว้กรอก URL
  2. กดปุ่ม ตกลงเราจะระมัดระวัง
  3. จะเข้าอีกหน้าหนึ่ง ตรงช่องค้นหา (ด้านล่างนะครับ ไม่ใช่ช่องค้นหาปกติ) ใส่คำว่า Babylon ลงไป
  4. รายการจะเหลือแค่สิ่งที่เกี่ยวกับเจ้า Babylon จอมยุ่ง จะเห็นว่าสถานะจะขึ้นว่า ตั้งค่าโดยผู้ใช้ คลิกขวาบรรทัดนั้น เลือก กลับค่าเดิม ไล่เปลี่ยนบรรทัดอื่นให้หมด
  5. เปิด tab ใหม่ จะกลับไปเป็น Firefox แบบเดิมๆครับ