Tag Archive google maps apis

google maps: หาจุดศูนย์กลาง

ถ้าชอบภาพยนตร์สืบสวนสอบสวนอย่าง cis, ncis อาจจะคุ้นกับการลากจุดศูนย์กลางของเสาสัญญาน 3 เสา เพื่อหาว่าคนร้ายโทรมาจากที่ไหน หรือ ใน criminal minds จะใช้การลากเส้นจุดก่อเหตุดูว่าคนร้ายอยู่ที่ไหน

จากตัวอย่างที่แล้วๆมาจุดที่ mark ไว้มันมันกระจัดกระจาย ถึงจะเริ่มต้นโดยการเลือกโรงพญาบาลบริเวณอนุสาวรีย์ชัยสมรภูมิ แต่กลับดูกระจัดกระจาย การจัด setCenter ใหม่จะทำให้เห็นได้ชัดเจนขึ้นโดยใช้หลักการเดียวกัน

การหาจุดศูนย์กลางทำได้โดยใช้[code language=”javascript” title=”getCenter”]function getCenter(map, places) {
$X = 0.0;
$Y = 0.0;
$Z = 0.0;
var placesLength = places.length;
for (var a = 0; a < placesLength; a++) {
place = places[a];

$lat = place.latitude * Math.PI / 180;
$lon = place.longitude * Math.PI / 180;
$a = Math.cos($lat) * Math.cos($lon);
$b = Math.cos($lat) * Math.sin($lon);
$c = Math.sin($lat);
$X += $a;
$Y += $b;
$Z += $c;
}
$X /= placesLength;
$Y /= placesLength;
$Z /= placesLength;
$lon = Math.atan2($Y, $X);
$hyp = Math.sqrt($X * $X + $Y * $Y);
$lat = Math.atan2($Z, $hyp);

var latitude = $lat * 180 / Math.PI;
var longitude = $lon * 180 / Math.PI;

var latlng = new google.maps.LatLng(latitude, longitude);
map.setCenter(latlng);

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

var infowindow = new google.maps.InfoWindow({
"content": "setCenter Latitude = " + latitude + ", " + " longitude = " + longitude,
"position": latlng,
}).open(map, marker);
}[/code]

และเช่นเดียวกับเรื่องอื่น คุณดูตัวอย่างได้จาก google maps: setCenter หรือจะเขียน code[code language=”html” title=”marker.multiple.setCenter.html”]<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps APIs > Maps JavaScript API > Markers > setCenter</title>
<link href="../../vendor/twbs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" rel="stylesheet" type="text/css">
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="map" id="mapA"></div>
<br>
<button class="btn" id="deleteBtn" type="button">Delete Marker</button>
<script src="../../vendor/components/jquery/jquery.min.js"></script>
<script>
var map;
var overlays = [];
var places = [{
"latitude": 13.7485809,
"longitude": 100.5832588,
"name_en": "Bangkok Hospital",
"name_th": "โรงพยาบาล กรุงเทพ ซอยศูนย์วิจัย"
}, {
"latitude": 13.746166,
"longitude": 100.552348,
"name_en": "Bumrungrad International Hospital",
"name_th": "โรงพยาบาล บำรุงราษฎร์"
}, {
"latitude": 13.7679658,
"longitude": 100.5345264,
"name_en": "Phramongkutklao Hospital",
"name_th": "โรงพยาบาลพระมงกุฎเกล้า"
},
{
"latitude": 13.7561676,
"longitude": 100.5391023,
"name_en": "Phyathai 1 Hospital",
"name_th": "โรงพยาบาล พญาไท 1"
}, {
"latitude": 13.7698357,
"longitude": 100.5404377,
"name_en": "Phyathai 2 Hospital",
"name_th": "โรงพยาบาล พญาไท 2 อินเตอร์เนชันแนล"
},
{
"latitude": 13.769295,
"longitude": 100.527455,
"name_en": "Prasat Neurological Hospital and Institute",
"name_th": "สถาบันประสาทวิทยา"
}, {
"latitude": 13.76188,
"longitude": 100.526455,
"name_en": "Priest Hospital",
"name_th": "โรงพยาบาลสงฆ์"
}, {
"latitude": 13.7659465,
"longitude": 100.5353223,
"name_en": "Queen Sirikit National Institute of Child Health",
"name_th": "สถาบันสุขภาพเด็กแห่งชาติมหาราชินี"
}, {
"latitude": 13.7642952,
"longitude": 100.5367674,
"name_en": "Rajavithi Hospital",
"name_th": "โรงพยาบาล ราชวิถี"
},
{
"latitude": 13.766015,
"longitude": 100.5267864,
"name_en": "Ramathibodi Hospital",
"name_th": "โรงพยาบาลรามาธิบดี"
},
{
"latitude": 13.7657804,
"longitude": 100.5333703,
"name_en": "TropMed Hospital for Tropical Diseases – Faculty of Tropical Medicine, Mahidol University",
"name_th": "โรงพยาบาล เวชศาสตร์เขตร้อน ม.มหิดล"
}, {
"latitude": 13.7719828,
"longitude": 100.5515745,
"name_en": "Veterans General Hospital",
"name_th": "โรงพยาบาล ทหารผ่านศึก"
}, {
"latitude": 13.7831277,
"longitude": 100.5336353,
"name_en": "Vichaiyut Hospital (North Building)",
"name_th": "โรงพยาบาล วิชัยยุทธ"
}, {
"latitude": 13.7804061,
"longitude": 100.5330211,
"name_en": "Vichaiyut Medical Center",
"name_th": "ศูนย์การแพทย์วิชัยยุทธ"
}, {
"latitude": 13.7600024,
"longitude": 100.534462,
"name_en": "Bhumirajanakarindra Kidney Institute Hospital",
"name_th": "โรงพยาบาล สถาบันโรคไตภูมิราชนครินทร์"
}
];

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

map.setCenter(latlng);

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

var infowindow = new google.maps.InfoWindow({
"content": ‘Latitude = ‘ + position.latitude + ‘, ‘ + ‘ longitude = ‘ + position.longitude,
"position": latlng,
}).open(map, marker);

}

function deleteOverlays() {
var overlaysLength = overlays.length;
if (overlaysLength > 1) {
for (var a = 0; a <= overlays.length; a++) {
if (typeof overlays[a] !== ‘undefined’) {
overlays[a].setMap(null);
}
}
}
overlays = [];
}

function getCenter(map, places) {
$X = 0.0;
$Y = 0.0;
$Z = 0.0;
var placesLength = places.length;
for (var a = 0; a < placesLength; a++) {
place = places[a];

$lat = place.latitude * Math.PI / 180;
$lon = place.longitude * Math.PI / 180;
$a = Math.cos($lat) * Math.cos($lon);
$b = Math.cos($lat) * Math.sin($lon);
$c = Math.sin($lat);
$X += $a;
$Y += $b;
$Z += $c;
}
$X /= placesLength;
$Y /= placesLength;
$Z /= placesLength;
$lon = Math.atan2($Y, $X);
$hyp = Math.sqrt($X * $X + $Y * $Y);
$lat = Math.atan2($Z, $hyp);

var latitude = $lat * 180 / Math.PI;
var longitude = $lon * 180 / Math.PI;

var latlng = new google.maps.LatLng(latitude, longitude);
map.setCenter(latlng);

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

var infowindow = new google.maps.InfoWindow({
"content": "setCenter Latitude = " + latitude + ", " + " longitude = " + longitude,
"position": latlng,
}).open(map, marker);
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
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 = {
"latitude": defaultLatitude,
"longitude": defaultLongitude,
};

createMap(‘mapA’, position);

setMarkers(map)
}

function setMarkers(map) {
var placesLength = places.length;
for (var a = 0; a < placesLength; a++) {
var place = places[a];
var marker = new google.maps.Marker({
"map": map,
"position": {
"lat": parseFloat(place.latitude),
"lng": parseFloat(place.longitude)
},
"title": place.name_en + "\n" + place.name_th,
"zIndex": a
});

overlays.push(marker);
}

getCenter(map, places);
}

$(function() {
$(‘#deleteBtn’).click(function() {
deleteOverlays();
});
});
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyDE5zb4r9sbN5S_GcD3NZRED1Ma3FzFqso"></script>
</body>
</html>[/code]

google maps: สร้าง markers หลายตำแหน่ง

google maps api สามารถสร้าง marker หลายตำแหน่งในแผนที่เดียวกันได้ อาจจะใช้ในการสร้างแผนที่สาขา หรือจะเป็นโรงพญาบาลในบริเวณนั้นก็ได้

จุดสำคัญคือตำแหน่ง gps ถ้าต้องการให้ได้ตำแหน่งที่ตรงกับ position ในแผนที่จริงๆ แทนที่จะต้องเดินไป เช็คตำแหน่ง gps ในมือถือ ใช้วิธีดูเอาจากแผนที่ของ google เองจะตรงกว่า ตัวอย่างผมเปิดแผนที่ อนุสาวรีย์ชัยสมรภูมิ จากนั้นคลิกที่ โรงพญาบาล จะมี info windows เปิดขึ้นมา จากนั้นให้คลิกขวา เปิดใน tab ใหม่ เช่น โรงพยาบาลรามาธิบดี จะได้ url เช่น https://www.google.com/maps/place/%E0%B9%82%E0%B8%A3%E0%B8%87%E0%B8%9E%E0%B8%A2%E0%B8%B2%E0%B8%9A%E0%B8%B2%E0%B8%A5%E0%B8%A3%E0%B8%B2%E0%B8%A1%E0%B8%B2%E0%B8%98%E0%B8%B4%E0%B8%9A%E0%B8%94%E0%B8%B5/@13.7760601,100.522649,15z/data=!4m12!1m6!3m5!1s0x0:0xc4dd9b398f456bcf!2z4LmC4Lij4LiH4Lie4Lii4Liy4Lia4Liy4Lil4Lij4Liy4Lih4Liy4LiY4Li04Lia4LiU4Li1!8m2!3d13.766015!4d100.5267864!3m4!1s0x30e2994da99aa1fd:0xc4dd9b398f456bcf!8m2!3d13.766015!4d100.5267864 จากนั้น ก็ดูที่ !3d จะตามด้วยเลข latitude และ !4d จะเป็นเลข longitude ของจุดที่ google plot ตำแหน่งเอาไว้

[code language=”html” title=”marker.multiple.html”]<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps APIs > Maps JavaScript API > Markers</title>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="map" id="mapA"></div>
<script src="../../vendor/components/jquery/jquery.min.js"></script>
<script>
var map;
var places = [{
"latitude": 13.7485809,
"longitude": 100.5832588,
"name_en": "Bangkok Hospital",
"name_th": "โรงพยาบาล กรุงเทพ ซอยศูนย์วิจัย"
}, {
"latitude": 13.746166,
"longitude": 100.552348,
"name_en": "Bumrungrad International Hospital",
"name_th": "โรงพยาบาล บำรุงราษฎร์"
}, {
"latitude": 13.7679658,
"longitude": 100.5345264,
"name_en": "Phramongkutklao Hospital",
"name_th": "โรงพยาบาลพระมงกุฎเกล้า"
},
{
"latitude": 13.7561676,
"longitude": 100.5391023,
"name_en": "Phyathai 1 Hospital",
"name_th": "โรงพยาบาล พญาไท 1"
}, {
"latitude": 13.7698357,
"longitude": 100.5404377,
"name_en": "Phyathai 2 Hospital",
"name_th": "โรงพยาบาล พญาไท 2 อินเตอร์เนชันแนล"
},
{
"latitude": 13.769295,
"longitude": 100.527455,
"name_en": "Prasat Neurological Hospital and Institute",
"name_th": "สถาบันประสาทวิทยา"
}, {
"latitude": 13.76188,
"longitude": 100.526455,
"name_en": "Priest Hospital",
"name_th": "โรงพยาบาลสงฆ์"
}, {
"latitude": 13.7659465,
"longitude": 100.5353223,
"name_en": "Queen Sirikit National Institute of Child Health",
"name_th": "สถาบันสุขภาพเด็กแห่งชาติมหาราชินี"
}, {
"latitude": 13.7642952,
"longitude": 100.5367674,
"name_en": "Rajavithi Hospital",
"name_th": "โรงพยาบาล ราชวิถี"
},
{
"latitude": 13.766015,
"longitude": 100.5267864,
"name_en": "Ramathibodi Hospital",
"name_th": "โรงพยาบาลรามาธิบดี"
},
{
"latitude": 13.7657804,
"longitude": 100.5333703,
"name_en": "TropMed Hospital for Tropical Diseases – Faculty of Tropical Medicine, Mahidol University",
"name_th": "โรงพยาบาล เวชศาสตร์เขตร้อน ม.มหิดล"
}, {
"latitude": 13.7719828,
"longitude": 100.5515745,
"name_en": "Veterans General Hospital",
"name_th": "โรงพยาบาล ทหารผ่านศึก"
}, {
"latitude": 13.7831277,
"longitude": 100.5336353,
"name_en": "Vichaiyut Hospital (North Building)",
"name_th": "โรงพยาบาล วิชัยยุทธ"
}, {
"latitude": 13.7804061,
"longitude": 100.5330211,
"name_en": "Vichaiyut Medical Center",
"name_th": "ศูนย์การแพทย์วิชัยยุทธ"
}, {
"latitude": 13.7600024,
"longitude": 100.534462,
"name_en": "Bhumirajanakarindra Kidney Institute Hospital",
"name_th": "โรงพยาบาล สถาบันโรคไตภูมิราชนครินทร์"
}
];

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

map.setCenter(latlng);

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

var infowindow = new google.maps.InfoWindow({
"content": ‘Latitude = ‘ + position.latitude + ‘, ‘ + ‘ longitude = ‘ + position.longitude,
"position": latlng,
}).open(map, marker);

}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
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 = {
"latitude": defaultLatitude,
"longitude": defaultLongitude,
};

createMap(‘mapA’, position);

setMarkers(map)
}

function setMarkers(map) {
for (var a = 0; a < places.length; a++) {
var place = places[a];
var marker = new google.maps.Marker({
"map": map,
"position": {
"lat": parseFloat(place.latitude),
"lng": parseFloat(place.longitude)
},
"title": place.name_en + "\n" + place.name_th,
"zIndex": a
});
}
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyDE5zb4r9sbN5S_GcD3NZRED1Ma3FzFqso"></script>
</body>
</html>[/code]

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

google maps: สร้างและลบ marker / overlay

google maps: สร้างและลบ marker / overlay

google map api มอง marker และ infowindows เป็น overlay ประเภทหนึ่งที่สามารถลบได้โดยการเพิ่มใน array overlays และเปลี่ยนให้เป็น null เหมือนๆกัน

คลิกเพื่อดูตัวอย่าง google maps: สร้างและลบ marker / overlay หรือจะเขียนเองตามตัวอย่างก็ได้[code language=”html” title=”marker.multiple.delete.html”]<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps APIs > Maps JavaScript API > Markers > delete overlay</title>
<link href="../../vendor/twbs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" rel="stylesheet" type="text/css">
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="map" id="mapA"></div>
<br>
<button class="btn" id="deleteBtn" type="button">Delete Marker</button>
<script src="../../vendor/components/jquery/jquery.min.js"></script>
<script>
var map;
var overlays = [];
var places = [{
"latitude": 13.7485809,
"longitude": 100.5832588,
"name_en": "Bangkok Hospital",
"name_th": "โรงพยาบาล กรุงเทพ ซอยศูนย์วิจัย"
}, {
"latitude": 13.746166,
"longitude": 100.552348,
"name_en": "Bumrungrad International Hospital",
"name_th": "โรงพยาบาล บำรุงราษฎร์"
}, {
"latitude": 13.7679658,
"longitude": 100.5345264,
"name_en": "Phramongkutklao Hospital",
"name_th": "โรงพยาบาลพระมงกุฎเกล้า"
},
{
"latitude": 13.7561676,
"longitude": 100.5391023,
"name_en": "Phyathai 1 Hospital",
"name_th": "โรงพยาบาล พญาไท 1"
}, {
"latitude": 13.7698357,
"longitude": 100.5404377,
"name_en": "Phyathai 2 Hospital",
"name_th": "โรงพยาบาล พญาไท 2 อินเตอร์เนชันแนล"
},
{
"latitude": 13.769295,
"longitude": 100.527455,
"name_en": "Prasat Neurological Hospital and Institute",
"name_th": "สถาบันประสาทวิทยา"
}, {
"latitude": 13.76188,
"longitude": 100.526455,
"name_en": "Priest Hospital",
"name_th": "โรงพยาบาลสงฆ์"
}, {
"latitude": 13.7659465,
"longitude": 100.5353223,
"name_en": "Queen Sirikit National Institute of Child Health",
"name_th": "สถาบันสุขภาพเด็กแห่งชาติมหาราชินี"
}, {
"latitude": 13.7642952,
"longitude": 100.5367674,
"name_en": "Rajavithi Hospital",
"name_th": "โรงพยาบาล ราชวิถี"
},
{
"latitude": 13.766015,
"longitude": 100.5267864,
"name_en": "Ramathibodi Hospital",
"name_th": "โรงพยาบาลรามาธิบดี"
},
{
"latitude": 13.7657804,
"longitude": 100.5333703,
"name_en": "TropMed Hospital for Tropical Diseases – Faculty of Tropical Medicine, Mahidol University",
"name_th": "โรงพยาบาล เวชศาสตร์เขตร้อน ม.มหิดล"
}, {
"latitude": 13.7719828,
"longitude": 100.5515745,
"name_en": "Veterans General Hospital",
"name_th": "โรงพยาบาล ทหารผ่านศึก"
}, {
"latitude": 13.7831277,
"longitude": 100.5336353,
"name_en": "Vichaiyut Hospital (North Building)",
"name_th": "โรงพยาบาล วิชัยยุทธ"
}, {
"latitude": 13.7804061,
"longitude": 100.5330211,
"name_en": "Vichaiyut Medical Center",
"name_th": "ศูนย์การแพทย์วิชัยยุทธ"
}, {
"latitude": 13.7600024,
"longitude": 100.534462,
"name_en": "Bhumirajanakarindra Kidney Institute Hospital",
"name_th": "โรงพยาบาล สถาบันโรคไตภูมิราชนครินทร์"
}
];

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

map.setCenter(latlng);

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

var infowindow = new google.maps.InfoWindow({
"content": ‘Latitude = ‘ + position.latitude + ‘, ‘ + ‘ longitude = ‘ + position.longitude,
"position": latlng,
}).open(map, marker);

}

function deleteOverlays() {
var overlaysLength = overlays.length;
if (overlaysLength > 1) {
for (var a = 0; a <= overlays.length; a++) {
if (typeof overlays[a] !== ‘undefined’) {
overlays[a].setMap(null);
}
}
}
overlays = [];
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
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 = {
"latitude": defaultLatitude,
"longitude": defaultLongitude,
};

createMap(‘mapA’, position);

setMarkers(map)
}

function setMarkers(map) {
for (var a = 0; a < places.length; a++) {
var place = places[a];
var marker = new google.maps.Marker({
"map": map,
"position": {
"lat": parseFloat(place.latitude),
"lng": parseFloat(place.longitude)
},
"title": place.name_en + "\n" + place.name_th,
"zIndex": a
});

overlays.push(marker);
}
}

$(function(){
$(‘#deleteBtn’).click(function(){
deleteOverlays();
});
});
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyDE5zb4r9sbN5S_GcD3NZRED1Ma3FzFqso"></script>
</body>
</html>[/code]

google maps: HTML5.Geolocation

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

แต่เพราะมันกระทบถึงความเป็นส่วนตัว ในการเขียนจึงต้องเผื่อว่า user ไม่อนุญาตให้ส่งตำแหน่งของตัวเองกลับมาไว้ด้วย ในตัวอย่างใช้ [code language=”javascript” title=”function getGeolocation”]/* 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;
}[/code] ส่ง position กลับมา ให้[code language=”javascript” title=”function initMap”]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);
}[/code]แต่ถ้าหากไม่มีพิกัดส่งมา จะนำค่า default มาแสดงแทน

คุณสามารถดูตัวอย่างได้จาก google maps: HTML5.Geolocation หรือลองสร้างไฟล์ตามตัวอย่าง[code language=”html” title=”HTML5.Geolocation.html”]<!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>[/code]

google maps: basic

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

  1. เริ่มจาก ขอ Google API key ก่อน
  2. จากนั้นลองสร้าง code ง่ายๆ ตามตัวอย่าง[code language=”css” title=”maps styles”]
    .map {
    border: #c00000 solid thin;
    height: 100%;
    min-height: 500px;
    }[/code]ส่วนนี้จะเป็น css class ที่ทำให้แน่ใจว่า พื้นที่แสดงแผนที่เห็นสูงอย่างน้อย 500 px เพราะว่าตัว google maps จะเอาความสูงของ div เอาไปใช้ ถ้าไม่กำหนดไว้ถึงสร้างแผนที่ได้ก็อาจจะมองไม่เห็น
  3. สร้างพื้นที่ไว้แสดงแผนที่ กำหนดให้ id=”mapA”[code language=”html” title=”ส่วนแสดงแผนที่”]<div class="map" id="mapA"></div>[/code]
  4. สร้างแผนที่[code language=”javascript” title=”function javascript สร้างแผนที่”]/* 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);
    }[/code]

  5. โหลด Google Maps APIs โดยใช้[code language=”html”]<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=YOUR_API_KEY"></script>[/code]แทนที่ YOUR_API_KEY เป็น key ของเราเอง โดย callback= ตามด้วย function ที่ใช้สร้างแผนที่ หรือ function อื่นๆ ที่จะให้ทำงานหลังโหลดเพจเสร็จ ตามตัวอย่างคือ function initMap จะไม่สร้างแผนที่โดยตรงแต่จะใช้ function createMap สร้างให้อีกที ถ้าต้องการสร้างแผนที่เพิ่ม แค่เรียกใช้[code language=”javascript” title=”วิธีสร้างแผนที่”]createMap(‘พื้นที่แสดงแผนที่’, {
    "latitude": ค่า latitude,
    "longitude": ค่า longitude,
    });[/code]ก็จะมีแผนที่ที่มีหน้าตาคล้ายๆอีกอันเพิ่มขึ้นมา

ดูตัวอย่างได้ที่ google maps: basic หรือจะลองสร้างไฟล์เอง[code language=”css” title=”styles.css”]@charset "utf-8";
/* CSS Document */
.map {
border: #c00000 solid thin;
height: 100%;
min-height: 500px;
}[/code][code language=”html” title=”Google Maps APIs > Maps JavaScript API > Simple Map”]<!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>[/code]

การกำหนด function ให้ทำงานหลังโหลดเพจเสร็จนอกจากใช้ตัวแปร callback แล้วยังสามารถใช้[code language=”javascript” title=”เรียก function หลังเพจโหลดเสร็จ”]google.maps.event.addDomListener(window, ‘load’, initMap);[/code]ได้เหมือนกัน

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