本文实现google maps API主要的函数库
html:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Chapter11index.aspx.cs"
Inherits="GoogleMaps.Chapter11index" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>地图搜索</title>
<style type="text/css">
@import url("http://www.google.com/uds/css/gsearch.css");
@import url("http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css");
/*common*/div, p, a, span
{
font-size: 13px;
margin: 0;
padding: 0;
border: 0;
}
.wrapper
{
width: 100%;
padding: 2px;
border: 1px solid #979797;
}
/*map-container*/.map-container
{
width: 640px;
height: 500px;
}
.result-panel
{
display: none;
}
/*info-window*/.info-title
{
width: 100%;
padding: 2px 5px;
font-weight: bolder;
font-size: 1.1em;
}
.info-paragraph
{
width: 220px;
float: left;
margin-top: 5px;
}
.info-tip
{
font-size: 0.9em;
color: #666;
margin-bottom: 3px;
}
/*tab*/.tab-head
{
width: 100%; /*height:1.5em;
background-color:#cfcfcf;*/
overflow: auto;
border-bottom: solid #CCD9F2 1px;
}
.tab-item
{
text-align: center;
float: left;
padding: 1px 5px;
cursor: pointer;
color: #0000FF;
}
.active-tab
{
/*border:solid #666666 1px;
border-bottom:solid #FFF 1px;
background-color:#FFF;*/
color: #000;
font-weight: bold;
text-decoration: none;
}
.tab-content
{
padding-top: 5px;
display: none;
}
.wrapper .gmls
{
width: 100%;
}
.wrapper .gmls-app
{
border: none;
}
.wrapper .gmls-search-form
{
padding: 2px;
margin: 0;
}
.info-button, .traffic-button
{
border: #000000 solid 1px;
background-color: #FFF;
padding: 1.5px 4px;
cursor: pointer;
}
.wrapper .googledir, .wrapper .googledir table, .wrapper .googledir td, .wrapper .googledir div
{
font-size: 12px;
margin: 0;
padding: 0;
}
</style>
<!-- 添加如下的引用,则可以使用goolge命名空间中的很多对象 -->
<script src="http://www.google.com/jsapi?hl=zh-CN&key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA"
type="text/javascript"></script>
<script src="http://ditu.google.cn/?file=api&v=2.x&hl=zh-CN&key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA"
type="text/javascript"></script>
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA&hl=zh-CN"
type="text/javascript"></script>
<script src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div class="wrapper" id="wrapper">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td valign="top" style="padding-right: 10px" width="40%">
<div class="map-container" id="mapContainer">
</div>
</td>
<td valign="top">
<!-- 加载地图时的动画图片 -->
<img style="padding: 5px;" id="loadingImg" src="loading_circle.gif" />
<!-- 用于显示查询结果 -->
<div class="result-panel" id="localResult">
</div>
<!-- 用于显示线路结果 -->
<div class="result-panel" id="routeResult">
</div>
</td>
</tr>
</table>
</div>
<script type="text/javascript" src="initMap11.js"></script>
</form>
</body>
</html>
initMap11.js:
var $ = function(id) {
return document.getElementById(id);
}
function $n(tag, ptr, className) {
var el = document.createElement(tag);
el.className = className || "";
if (ptr)
ptr.appendChild(el);
return el;
}
var map;
var isUsingDefault;
var location = {};
var localResult = {};
var routeResult = {};
var routeControl = null;
var localControl = null;
var localDom = $("localResult");
var routeDom = $("routeResult");
var infoTabkeys = { route: "route", transit: "transit", near: "near" };
var apiKey = "ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1 - m51RBrvYughuyMxQ - i1QfUnH94QxWIa6N4U6MouMmBA";
getLocationByPrefs();
function getLocationByPrefs() {
isUsingDefault = true;
var lat = null;
var lng = null;
if (isUsingDefault && lat && lng) {
location.lat = parseFloat(lat);
location.lng == parseFloat(lng);
initMap();
}
else {
var defLoc = "chengdu";
if (defLoc) {
var geocoder = new GClientGeocoder();
geocoder.getLocations(defLoc, function(response) {
if (response) {
var place = response.Placemark[0];
location.lat = place.Point.coordinates[1];
location.lng = place.Point.coordinates[0];
}
else {
getLocationByIP();
}
initMap();
});
}
else {
getLocationByIP();
initMap();
}
}
}
function getLocationByIP() {
if (google.loader && google.loader.ClientLocation) {
var loc = google.loader.ClientLocation;
if (loc.latitude && loc.longitude) {
location.lat = loc.latitude;
location.lng = loc.longitude;
}
}
}
function initMap() {
location.zoom = 10;
location.lat = location.lat || 39.9056;
location.lng = location.lng || 116.3958;
map = new GMap2($("mapContainer"));
map.setCenter(new GLatLng(location.lat, location.lng), location.zoom);
map.enableContinuousZoom();
map.enableScrollWheelZoom();
//map.addControl(new GLargeMapControl());
map.setUIToDefault();
map.addControl(new GMenuMapTypeControl());
map.addMapType(G_PHYSICAL_MAP);
map.addControl(new TrafficButton());
new GKeyboardHandler(map);
searchLoaded();
}
function searchLoaded() {
var options = { resultList: localDom,
searchFormHint: "/u63d0/u793a/uff1a/u7f29/u653e/u5730/u56fe/u5230/u76ee/u6807/u8303/u56f4/u5185/u53ef/u4ee5/u641c/u7d22/u5230/u66f4/u7cbe/u786e/u7684/u7ed3/u679c/uff01",
onIdleCallback: onSearchIdle,
onSearchCompleteCallback: clearRouteResult,
onMarkersSetCallback: onSearchLoaded,
onGenerateMarkerHtmlCallback: genInfoWindowHtml
};
localControl = new google.maps.LocalSearch(options);
$("loadingImg").style.display = "none";
map.addControl(localControl, new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(0, -10)));
searcher = localControl.gs;
map.getContainer().style.marginBottom = "26px";
adjusHeight();
localControl.focus();
var query = "好又多";
if (query) {
localControl.newSearch(query);
}
}
function onSearchIdle() {
localDom.style.display = "none";
adjusHeight();
}
function clearRouteResult() {
if (routeResult.polyline) {
map.removeOverlay(routeResult.polyline);
routeResult.polyline = null;
}
if (routeResult.markers) {
for (var i = routeResult.markers.length - 1, marker; i >= 0; i--) {
map.removeOverlay(routeResult.markers[i]);
}
routeResult.markers = null;
}
routeDom.style.display = "none";
}
function onSearchLoaded() {
localDom.style.display = "block";
if (localDom.clientHeight > 185) {
localDom.style.height = 185 + "px";
}
adjusHeight();
var elems = localDom.getElementsByTagName("a");
for (var i = 0; i < elems.lengthl; i++) {
if (elems[i].className == "gmls-more-results") {
elems[i].href = getDituUrl() + "&f=q&q=" + encodeURIComponent(searcher.ne);
}
}
}
function adjusHeight() {
map.checkResize();
}
function genInfoWindowHtml(marker, html, result) {
localResult.curResult = result;
localResult.marker = marker;
var dom = $n("div");
var link = getDituUrl() + "&f=q&q=" + encodeURIComponent(result.titleNoFormatting);
var li = marker.getPoint().lat() + "," + marker.getPoint().lng();
var zoom = map.getZoom() > 13 ? 10 : 15;
var staticUrl = "http://ditu.google.cn/staticmap?center=" + li + "&zoom=" + zoom + "&size=100x67&markers=" + li + ",red&key=" + apiKey;
//开始显示信息窗口的标题
var html = "<div style=/"width:220px;/">" + "<p class=/"info-title/">" + result.titleNoFormatting + "</p>" + "<p style=/"width:95%;text-align:right;/">";
//添加信息窗口的图中图及去主页查看信息的连接,同时添加onclick事件.
html += "<a href=/"" + link + "/" target=/"_blank/">/u53bb/u5730/u56fe/u4e3b/u9875/u67e5/u770b/u66f4/u591a/u4fe1/u606f</a></p>" + "<div class=/"info-paragraph/">" + "<p style=/"float:right;height:67px;width:100px;/"><img style=/"border:solid #0000CC 1px;cursor:pointer;height:67px;width:100px;/" src=/"" + staticUrl + "/" onclick=/"magnifyMap()/"/><br/>" + "</p>";
//添加信息窗口的地址信息
if (result.streetAddress) {
html += "<p style=/"width:110px;/"><span>/u5730/u5740/uff1a</span></p>" + "<p style=/"width:100px;padding-left:1em;/">" + result.streetAddress + "</p>";
}
//添加信息窗口的电话信息
if (result.phoneNumbers) {
html += "<p style=/"width:110px;/"><span>/u7535/u8bdd/uff1a</span></p>" + "<p style=/"width:100px;padding-left:1em;/">" + result.phoneNumbers[0].number + "</p>";
}
html += "</div>";
//----第一部分信息结束
//----第二部分信息开始
html += "<div class=/"info-paragraph/">" +
//添加三个tab
"<div class=/"tab-head/">" +
//在附近搜索,添加onclick,onmouseout,onmouseover事件
"<p class=/"tab-item active-tab/" id=/"near_tab/" onclick=/"onInfoTabClick('near');/" onmouseout=/"this.style.textDecoration='none'/" onmouseover=/"onInfoTabMouseover(this)/">/u5728/u9644/u8fd1/u641c/u7d22</p>" +
//驾车路线
"<p class=/"tab-item/" id=/"route_tab/" onclick=/"onInfoTabClick('route');/" onmouseout=/"this.style.textDecoration='none'/" onmouseover=/"onInfoTabMouseover(this)/">/u9a7e/u8f66/u8def/u7ebf</p>" +
//公交路线
"<p class=/"tab-item/" id=/"transit_tab/" onclick=/"onInfoTabClick('transit');/" onmouseout=/"this.style.textDecoration='none'/" onmouseover=/"onInfoTabMouseover(this)/">/u516c/u4ea4/u8def/u7ebf</p>" +
"</div>" +
//在附近搜索
"<div id=/"near_cnt/" class=/"tab-content/" style=/"display:block;/">" + "<p class=/"info-tip/"><span>/u4f8b/u5982/uff1a/u4e1c/u57ce/u533a /u4e66/u5e97</span></p>" +
//在附近搜索-搜索内容输入框
"<input type=/"text/" id=/"near_input/" style=/"width:75%/" class=/"gsc-input/" onkeydown=/"inputonkeydown(this, event)/"/>" +
//在附近搜索-搜索按钮
"<input type=/"button/" class=/"info-button gsc-search-button/" value=/"/u641c/u7d22/" onclick=/"getNear();/"/>" +
"</div>" +
//驾车路线
"<div id=/"route_cnt/" class=/"tab-content/" >" +
"<p class=/"info-tip/">" +
//驾车路线-输入目出发点
"<input type=/"radio/" name=/"route/" id=/"routeFrom/" checked=/"checked/"/>/u8f93/u5165/u76ee/u7684/u5730 " +
//车路线-输入目的地
"<input type=/"radio/" name=/"route/" id=/"routeTo/"/>/u8f93/u5165/u51fa/u53d1/u70b9 </p>" +
//驾车路线-搜索内容输入框
"<input type=/"text/" id=/"route_input/" style=/"width:75%/" class=/"gsc-input/" onkeydown=/"inputonkeydown(this, event)/"/>" +
//驾车路线-搜索按钮
"<input type=/"button/" class=/"info-button gsc-search-button/" value=/"/u641c/u7d22/" onclick=/"getRoute();/"/>" +
//驾车路线-错误或无结果的提示,例如"去谷歌地图主页试试"
"<p id=/"routeErrMsg/" style=/"display:none;color:#ff0000;margin-top:2px;/">/u6ca1/u6709/u627e/u5230/u6709/u6548/u7ed3/u679c/uff0c<a href=/"/" id=/"moreRouteLink/" target=/"_blank/">/u53bb/u8c37/u6b4c/u5730/u56fe/u4e3b/u9875/u8bd5/u8bd5</a></p>" +
"</div>" +
//公交路线
"<div id=/"transit_cnt/" class=/"tab-content/">" + "<p class=/"info-tip/">" +
//公交路线-输入目出发点
"<input type=/"radio/" name=/"transit/" id=/"transitFrom/" checked=/"checked/"/>/u8f93/u5165/u76ee/u7684/u5730 " +
//公交路线-输入目的地
"<input type=/"radio/" name=/"transit/" id=/"transitTo/"/>/u8f93/u5165/u51fa/u53d1/u70b9 </p>" +
//公交路线-搜索内容输入框
"<input type=/"text/" id=/"transit_input/" style=/"width:52%/" class=/"gsc-input/" onkeydown=/"inputonkeydown(this, event)/"/>" +
//公交路线--搜索连接
" <a class=/"info-button gsc-search-button/" style=/"border:none;/" href=/"javascript:getTransit();/">/u53bb/u5730/u56fe/u4e3b/u9875/u641c/u7d22</a>" +
"</div>" +
"</div>";
dom.innerHTML = html;
return dom;
}
function getDituUrl() {
var center = map.getCenter();
var span = map.getBounds().toSpan();
var ll = center.lat() + "," + center.lng();
var spn = span.lat() + "," + span.lng();
return "http://ditu.google.cn/maps?hl=zh-CN&ie=UTF8&sll=" + ll + "&sspn=" + spn; ;
}
function magnifyMap() {
var zoom = map.getZoom() > 13 ? 10 : 15;
map.setCenter(localResult.marker.getPoint(), zoom);
map.updateInfoWindow();
}
function onInfoTabClick(key) {
$(key + "_tab").className = "tab-item active-tab";
$(key + "_cnt").style.display = "block";
$(key + "_input").focus();
for (var i in infoTabkeys) {
if (infoTabkeys[i] != key) {
$(infoTabkeys[i] + "_tab").className = "tab-item";
$(infoTabkeys[i] + "_cnt").style.display = "none";
}
}
map.updateInfoWindow();
}
function onInfoTabMouseover(elem) {
if (elem.className && elem.className.indexOf("active-tab") == -1) {
elem.style.textDecoration = "underline";
}
}
function inputonkeydown(elem, e) {
e = e || window.event;
e.stopPropagation ? e.stopPropagation : e.cancelBubble = true;
var keyCode = e.keyCode || e.which || e.charCode;
if (keyCode == 13) {
if (elem.id == "route_input") {
getRoute();
}
else if (elem.id == "near_input") {
getNear();
}
else if (elem.id == "transit_input") {
getTransit();
}
}
}
function getNear() {
if (map.getZoom() < 16) {
map.setZoom(16);
}
var value = $("near_input").value;
if (value) {
localControl.newSearch(value);
}
}
function getRoute() {
if ($("routeFrom").checked) {
var from = $("route_input").value;
var to = localResult.curResult.streetAddress;
} else {
if ($("routeTo").checked) {
var from = localResult.curResult.streetAddress;
var to = $("route_input").value;
}
}
if (!routeControl) {
routeControl = new GDirections(map, routeDom);
GEvent.addListener(routeControl, "load", clearLocalResult);
GEvent.addListener(routeControl, "error", onRouteError);
GEvent.addListener(routeControl, "addoverlay", onRouteLoaded);
}
if (from && to) {
routeControl.load("from:" + from + " to:" + to);
}
}
function clearLocalResult() {
map.closeInfoWindow();
if (localResult.results) {
for (var i = 0, result; result = localResult.results[i]; i++) {
map.removeOverlay(result.marker);
}
localResult.results = null;
}
localDom.style.display = "none";
}
function onRouteError() {
if (!$("routeErrMsg")) {
return;
}
$("routeErrMsg").style.display = "block";
if ($("routeFrom").checked) {
var from = $("route_input").value;
var to = localResult.curResult.streetAddress;
} else {
if ($("routeTo").checked) {
var from = localResult.curResult.streetAddress;
var to = $("route_input").value;
}
}
$("moreRouteLink").href = getDituUrl() + "&f=d&saddr=" + encodeURIComponent(from) + "&daddr=" + encodeURIComponent(to);
map.updateInfoWindow();
return false;
}
function onRouteLoaded() {
routeDom.style.display = "block";
if (routeDom.clientHeight > 185) {
routeDom.style.height = 185 + "px";
}
adjustHeight();
routeResult.polyline = routeControl.getPolyline();
routeResult.markers = [routeControl.getMarker(0), routeControl.getMarker(1)];
GLog.write(routeControl.getSummaryHtml());
}
function getTransit() {
if ($("transitFrom").checked) {
var from = $("transit_input").value;
var to = localResult.curResult.streetAddress;
} else {
if ($("transitTo").checked) {
var from = localResult.curResult.streetAddress;
var to = $("transit_input").value;
}
if (from && to) {
var url = getDituUrl() + "&f=d&dirflg=r&saddr=" + encodeURIComponent(from) + "&daddr=" + encodeURIComponent(to);
window.open(url);
}
}
}
function TrafficButton() {
this.map;
this.button;
this.isShown = false;
this.trafficOl = new GTrafficOverlay();
}
TrafficButton.prototype = new GControl();
TrafficButton.prototype.initialize = function(map) {
this.map = map;
this.map.addOverlay(this.trafficOl);
var container = map.getContainer();
this.button = $n("div", container, "traffic-button");
this.button.innerHTML = '交通流量';
this.button.style.display = "";
GEvent.bind(this.trafficOl, "changed", this, this.toggleButton);
GEvent.bindDom(this.button, "click", this, this.toggleOverlay);
return this.button;
}
TrafficButton.prototype.toggleButton = function(hasTrafficInView) {
if (hasTrafficInView) {
this.button.style.display = "";
} else {
this.button.style.display = "none";
}
}
TrafficButton.prototype.toggleOverlay = function() {
if (this.isShown) {
this.isShown = false;
this.button.style.fontWeight = "normal";
this.trafficOl.hide();
} else {
this.isShown = true;
this.button.style.fontWeight = "bolder";
this.trafficOl.show();
}
}
TrafficButton.prototype.getDefaultPosition = function() {
return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(270, 7));
}
运行结果
更多源代码http://download.csdn.net/source/2913017
map3 API http://code.google.com/intl/zh-CN/apis/maps/documentation/javascript/reference.html