Google maps API开发(二)

这一篇主要实现怎么调用Google maps API中的地址解析核心类GClientGeocoder

主要功能包括地址解析、反向解析、本地搜索、周边搜索等,

我这里主要有两个实例:

实例一、当你搜索一个地名的时候,解析它的经纬度信息,并在地图上描点

实例二、搜索你的中心点所在区域的学校、商店等信息,并在地图上描点

首先来讲讲实例一怎么实现:

1、 加载google api

<script

type="text/javascript"src="http://ditu.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA&hl=zh-CN"></script>

2、 定义通用的全局变量和公共方法

var map;//GMap2的核心对象

var geocoder = null;//用来解析的

var markers = new Array();//用来存放GMarker

//======在地图上描点的方法============

function createMarker(icon, point, html, index) {

    var letter = String.fromCharCode("A".charCodeAt(0) + index);

    icon.image = "http://ditu.google.com/mapfiles/marker" + letter + ".png";

    var marker = new GMarker(point, icon);

    GEvent.addListener(marker, "click", function() {

        marker.openInfoWindowHtml(html);

    });

    markers.push(marker);

    map.addOverlay(marker);

}

//查询点击事件

function showLocation() {

    map.clearOverlays();

    document.getElementById('divOutput').innerHTML = "搜索中...";

    var address = document.getElementById('txtAddress').value;

    geocoder.getLocations(address, cb_showLocation);//搜索的核心方法

}

//回调事件,主要在界面上描点和右侧产生列表信息

function cb_showLocation(result) {

    // 显示结果

    if (result.Status.code == G_GEO_SUCCESS)

    {

        document.getElementById("divOutput").innerHTML = "成功(" + result.Placemark.length + ")<br />";

        var icon = new GIcon(G_DEFAULT_ICON);

        var lat, lng, point, address, marker;

        for (var i = 0; i < result.Placemark.length; i++) {

            lat = result.Placemark[i].Point.coordinates[1]; // lat

            lng = result.Placemark[i].Point.coordinates[0]; // lng

            address = result.Placemark[i].address; // 地址

            point = new GLatLng(lat, lng);

            document.getElementById("divOutput").innerHTML += ((i + 1) + " " + address + " <small>" + point.toString() + "</small><br />");

            createMarker(icon, point, address, i);

        }

    }

    else {

        document.getElementById("divOutput").innerHTML = result.Status.code;

    }

}

3、 地图初始化

function init() {

    //检查浏览器的兼容性.

    if (GBrowserIsCompatible()) {

        map = new GMap2(document.getElementById("map_canvas"));

        //设置地图的中心坐标.

        var loc = new GLatLng(39.990168, 116.295304);

        map.setCenter(loc, 5);

        //创建带有可在四个方向平移、放大、缩小的按钮,以及缩放滑块的控件。

        map.addControl(new GLargeMapControl());

        //创建带有切换地图类型的按钮的控件。

        map.addControl(new GMapTypeControl());

        //设置地图支持滚轮

        map.enableScrollWheelZoom();

        //实例化一个地址解析

        geocoder = new GClientGeocoder();

    }

}

4、 定义页面加载事件和卸载事件

window.onload = init;

window.onunload = GUnload;

//========主界面==================

<!-- 地图画板 -->

<input type="text" id="txtAddress" name="txtAddress" size="40" /><input type="button" value="查询" onclick="showLocation();" />

<div id="map_canvas" style="width: 600px; height: 500px ;float:left;"></div>

<div id="divOutput" style="float:left;" ></div>

//==============================

 

主要第一个例子就完成了,效果如下

 

实例二

1加载google api,这里用到三个

              <script   type="text/javascript" src="http://ditu.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA&hl=zh-CN"></script>

              <script type="text/javascript" src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA&hl=zh-CN"></script>

              <script type="text/javascript" src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js"></script>

2、通用核心类、全局变量和公共方法

var map;

var hasMarker = false;

var markers = new Array();

var KMapSearch = window.KMapSearch = function(map_, opts_)

{

    this.opts = { keyWord: opts_.keyWord || "", latlng: opts_.latlng || new GLatLng(31, 121), autoClear: opts_.autoClear || true, icon: opts_.icon || new GIcon(G_DEFAULT_ICON) };

    this.map = map_;

    this.gLocalSearch = new google.search.LocalSearch();

    this.gLocalSearch.setCenterPoint(this.opts.latlng);

    this.gLocalSearch.setResultSetSize(GSearch.LARGE_RESULTSET);

    this.gLocalSearch.setSearchCompleteCallback(this, myTips);

}

//请除所有查询结果

KMapSearch.prototype.clearAll = function() {

    for (var i = 0; i < markers.length; i++) { this.map.removeOverlay(markers[i]); }

    markers.length = 0;

}

//开始查询

KMapSearch.prototype.execute = function(latLng) {

    if (latLng) { this.gLocalSearch.setCenterPoint(latLng); }

    this.gLocalSearch.execute(this.opts.keyWord);

}

//取得查询结果,并以DIV的方式展示

KMapSearch.prototype.getResult = function(result, i) {

    var container = document.createElement("div");

    container.className = "list";

    var myRadom = (new Date()).getTime().toString() + Math.floor(Math.random() * 10000);

    container.id = myRadom;

    container.innerHTML = i + "" + result.title + "<br />地址:" + result.streetAddress;

    //this.createMarker(new GLatLng(result.lat, result.lng), result.html, myRadom);

    return container;

}

3、载入事件和辅助方法

//载入

function OnLoad() {

    if (GBrowserIsCompatible()) {

        map = new GMap2(document.getElementById("map_canvas"));

        map.addControl(new GLargeMapControl());

        map.addControl(new GMenuMapTypeControl());

        map.addControl(new GOverviewMapControl());

        map.enableScrollWheelZoom();

        map.setCenter(new GLatLng(39.990168, 116.295304), 10);

        //添加右键单击事件

        GEvent.addListener(map, "singlerightclick", function(point) {

            var initPt = map.fromContainerPixelToLatLng(point);

            map.clearOverlays();

            marker = new GMarker(initPt, { draggable: true });

            if (hasMarker) {

                marker.setLatLng(initPt);

                map.panTo(initPt);

            }

            else {

                //拖拽事件

                GEvent.addListener(marker, "dragend", function() {

                    initPt = marker.getLatLng();

                    map.panTo(initPt);

                    searchMap(initPt);

                });

                hasMarker = true;

            }

            map.addOverlay(marker);

            searchMap(initPt);

        });

    }

}

//点击提示信息

function myTips() {

    var content = "";

    var resultdiv = document.getElementById("map");

    for (j = 0; j < markers.length; j++) {

        map.removeOverlay(markers[j]);

    }

    markers.length = 0;

    var results = this.gLocalSearch.results;

    var icon = new GIcon(G_DEFAULT_ICON);

    var savedResults = document.getElementById("schollContainer");

    if (this.gLocalSearch.results)

    {

        if (this.opts.autoClear) {

            savedResults.innerHTML = "";

        }

        for (var i = 0; i < results.length; i++) {

            content = '<p>' + '名称:' + results[i].title + '<br />' + '地址:' + results[i].streetAddress + '<br />' + '坐标:' + results[i].lat + ',' + results[i].lng + '</p>';

            myCreateMarker(new GPoint(results[i].lng, results[i].lat), icon, content, i);

            savedResults.appendChild(this.getResult(this.gLocalSearch.results[i], i + 1));

        }

    }

}

//地图上标注

function myCreateMarker(point, icon, html, index) {

    var letter = String.fromCharCode("A".charCodeAt(0) + index);

    icon.image = "http://ditu.google.com/mapfiles/marker" + letter + ".png";

    var marker = new GMarker(point, icon);

    GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); });

    markers.push(marker);

    map.addOverlay(marker);

}

//在给定的坐标附近搜索指定的关键字

function searchMap(initPt) {

    var myIcon = new GIcon(G_DEFAULT_ICON);

    var mapSearch = new KMapSearch(map, { latlng: initPt, icon: myIcon, keyWord: "驾校" });

    mapSearch.clearAll();

    mapSearch.execute();

}

5、 最后

window.onload = OnLoad;

window.onunload = GUnload;

//========主界面==================

<!-- 地图画板 --> 

<div id="map_canvas" style="width:640px; height:480px ;float:left;"></div>

<div style="width:4px; height:480px ;float:left;"></div>

<div id="searchResult">驾校:<div id="schollContainer"></div></div>

//==============================

搞定, 最后的效果如图:

 

 

 源码实例下载

 

每天进步一点点...

posted @ 2010-03-30 13:46  洗碗心得  阅读(568)  评论(0编辑  收藏  举报