03 กุมภาพันธ์ 2012

VB.Net Google Maps

การทำแผนที่หาตำแหน่งตามต้องการด้วย VB.Net ก่อนอื่นเราต้องหาตำแหน่งให้ได้ก่อน
วิธีหนึ่งที่เราจะหาพิกัดในแผนที่ สามารถทำได้โดยเปิด Browser แล้วเข้าไปที่เว็บไซต์
http://maps.google.co.th/
จากนั้นทำการซูมแผนที่จนได้ตำแหน่งที่ต้องการ แล้วทำดังนี้
1. คลิกเมาส์ปุ่มขวา ณ. ตำแหน่งที่ต้องการทราบพิกัด แล้ว เลือกรายการนี่คืออะไร
2. จะปรากฏเลขพิกัด ลองติจูด, ละติจูด ปรากฏขึ้นตามภาพด้านล่าง






























สร้างฟอร์มแสดงแผนที่ ด้วย VB.Net
1. เปิดโปรแกรม Visual Studio 2010 แล้วสร้างโปรเจกต์ใหม่ โดย
    - คลิกเลือกเมนู File เลือกรายการ New Project...
    - ที่หน้าต่าง New Project เลือก Windows Form Application จาก Visual Basic -> Windows
    - ที่ช่อง New ในหน้าต่าง New Project ให้ตั้งชื่อตามต้องการ

2. ให้สร้างฟอร์มดังภาพ

























กำหนด Property ของคอนโทรลต่างๆ ดังนี้
Label1 : Text = Latitude
Label2 : Text = Longitude
Textbox1 : (Name) = txtLatidude
Textbox2 : (Name) = txtLongitude
Button1(Name) = btnSearch
                  Text = Search
WebBrowser1 : (Name) = WebBrowser1

ดับเบิ้ลคลิกที่ปุ่ม btnSearch แล้วเข้าไปเขียนโค้ดคำสั่ง ดังนี้

Imports System.Text

Public Class Form1
 Private Sub btnSearch_Click(ByVal sender As System.Object, _ 
          ByVal e As System.EventArgs) _
          Handles btnSearch.Click
  Try
    Dim latitude As String = ""
    Dim longitude As String = ""
    Dim AddrToSearch As New StringBuilder()
    AddrToSearch.Append("http://maps.google.com/maps?output=embed&hl=th&q=")
    ' if there is latitude
    If txtLatitude.Text <> "" Then
       latitude = txtLatitude.Text
       AddrToSearch.Append(latitude & "%2C")
    End If
    ' if there is longitude
    If txtLongitude.Text <> "" Then
       longitude = txtLongitude.Text
       AddrToSearch.Append(longitude)
    End If
    ' pass the AddrToSearch value to web browser control
    WebBrowser1.Navigate(AddrToSearch.ToString())
  Catch ex As Exception
    MessageBox.Show(ex.Message.ToString(), _
                    "Problem encountered while retrieving google map")
  End Try
 End Sub
End Class

ทำการเรียกฟอร์มที่เขียนไว้ให้ทำงาน โดยกดปุ่ม F5 จะปรากฎหน้าต่างของโปรแกรมให้ทำการป้อนค่าของพิกัด โดยใส่ ลองติจูดและ ละติจูด ที่ได้จากการหาตำแหน่งในตอนแรก แล้วคลิกปุ่ม Search จะปรากฏแผนที่แสดงตำแหน่งดังภาพ



























เราสามารถนำไปประยุกต์ใช้งานได้หลากหลาย สามารถนำไปใช้กับเว็บ นำไปใช้กับอุปกรณ์ GPS และอื่นๆ อีกมากมาย

3 กุมภาพันธ์ วันทหารผ่านศึก
"What you will become after reading this article ?"

Copyright(c) 2007 - 2012 by Kasem Kamolchaipisit.