`

使用google map显示地图,并标注InfoWindow

阅读更多
首先导入google map JS(需要VPN):
<script src="http://maps.google.com/maps/api/js?v=3.5&sensor=false&libraries=places"></script>

然后定义一个地图显示区域:
<div id="content_map"></div>

最后添加JS:
///////////////////////////////////////////////////////////////////////////////
//map start
//var geocoder;
var MY_POSITION="You are here";
var map;
var markersArray = [];
var latlng=null;
function initializeMap(position) {
	$("#content_map").width($(window).width()).height($(window).height()-40);
//	geocoder = new google.maps.Geocoder();
	if (typeof google === 'undefined') {
		log("================google is undefined================");
		return ;
	}
	if(position==null){
		latlng = new google.maps.LatLng(38.54,77.02);//华盛顿经纬度
	}else{
		latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
	}
	var myOptions = {
		zoom: 15,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	map = new google.maps.Map(document.getElementById("content_map"), myOptions);
}

function resizeMap(){
	if (!isNull(map)) {
		google.maps.event.trigger(map, 'resize');
		map.setCenter(latlng);
	}
}

function addMarker(location, item) {
	if (item === MY_POSITION) {
		var marker = new google.maps.Marker({
			position : location,
			title : MY_POSITION,
			map : map
		});
		markersArray.push(marker);
		
		var contentString = '<div style="color:black;text-align:center;">' +MY_POSITION+'</div>';
		var win = new google.maps.InfoWindow({
		   	content: contentString
		});
		google.maps.event.addListener(marker, 'click', function() {
			win.open(map, marker);
		});
	} else {
		var marker = new google.maps.Marker({
			position : location,
			title : item.storeName,
			// icon:"img/icon.png",
			map : map
		});
		markersArray.push(marker);
		
		var contentString = '<div style="color:black;text-align:center;">' +item.storeName+'<br />' +item.storeAddress+'</div>';
        
		var infowindow = new google.maps.InfoWindow({
		   	content: contentString
		});
		google.maps.event.addListener(marker, 'click', function() {
			// map.setZoom(15);
			// map.setCenter(marker.getPosition());
			infowindow.open(map, marker);
		});

		google.maps.event.addListener(marker, 'dblclick', function() {
			onStoreClick(item);
		});

	}
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
}

// Shows any overlays currently in the array
function showOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(map);
    }
  }
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}

/*
function codeAddress() {
	var address = document.getElementById("address").value;
	if (geocoder) {
		geocoder.geocode( { 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			map.setCenter(results[0].geometry.location);
			showAlert(results[0].geometry.location);
			var marker = new google.maps.Marker({
				map: map, 
				position: results[0].geometry.location
			});
		} else {
			showAlert("Geocode was not successful for the following reason: " + status);
		}
		});
	}
}
*/

//onSuccess Geolocation
function onGeoSuccess(position) {
	curPosition=position;
	doCommandFindStoreList(appConfig,user);
}

// onError Callback receives a PositionError object
function onGeoError(error) {
	onGeoSuccess(null);
}

var curPosition=null;//
function doCommandFindStoreList(appConfig,user){
	var senddata = {};
	senddata.sid = user.sid;
	senddata.companyId = appConfig.companyId;
	senddata.brandId = appConfig.brandId;
	if(curPosition!=null){
		senddata.latitude=curPosition.coords.latitude;
		senddata.longitude=curPosition.coords.longitude;
	}
	var require=$("#homepage #search").val().trim();
	if(require.length>0){
		senddata.require = require;
	}
	ajax(COMMAND_FIND_STORE_LIST,STORE_LIST_URL,senddata);
};

//map end
///////////////////////////////////////////////////////////////////////////////



使用cordova获取你当前的位置,成功的话执行onGeoSuccess,在该函数中查询门店位置信息:

if(navigator.geolocation){
var options = {
	enableHighAccuracy: true,
	maximumAge: 30000,
	timeout: 8000
};
					navigator.geolocation.getCurrentPosition(onGeoSuccess , onGeoError , options);
}else{//Geolocation is not supported by this browser.
	onGeoSuccess(null);
}


获取到所有经纬度信息之后再初始化map,并在map上添加marker:
case COMMAND_FIND_STORE_LIST:

		initializeMap(curPosition);

		$("#homepage #content_store_list").empty();
		$.each(data.listStroe,function(i,item){
			item.opening=isStoreOpen(item);
			var openStatus="<span style='font-size:12px;color:red;font-weight:normal;margin-left:10px;'>[OPEN]</span>";
			if(item.opening!=0){
				openStatus="<span style='font-size:12px;color:#666;font-weight:normal;margin-left:10px;'>"+getStoreOpenRemainingTime(item)+"</span>";
			}
			var distance="";
			if(curPosition!=null){
				if(item.latitude==null||item.longitude==null){
					
				}else{
					distance=GetDistance(item.latitude,item.longitude,curPosition.coords.latitude,curPosition.coords.longitude);//
				}
			}
			var display="inline";
			if(isNull(item.customerId)||item.customerId==0){
				display="none";
			}else{
				display="inline";
			}
			var itemStr=JSON.stringify(item);
			$("#homepage #content_store_list").append("<li class='li_item' onclick='onStoreClick("+itemStr+");'><div style='font-size:16px;font-weight:bold;margin-bottom:5px;'><span>"+item.storeName+"</span>"+openStatus+"<span style='float:right'><img style='display:"+display+"' src='img/my_favorite.png'/></span></div><div><span style='font-size:14px;'>"+item.storeAddress+"</span><div><span style='font-size:14px;'>"+item.city+","+item.provinceShrtNm+" "+item.zip+"</span><span style='font-size:14px;float:right;'>"+distance+"</span></div></div></li>");
			
			if(!isNull(map)){
				if(curPosition!=null){
					addMarker(map.getCenter(),MY_POSITION);
				}
	
				if(item.latitude!=null){
					var location = new google.maps.LatLng(item.latitude,item.longitude);
					addMarker(location,item);
				}
			}

		});

		break;


第一次地图显示的时候最好resize一下,使你的位置位于屏幕中心,refreshMap用于控制是否resizeMap,这样每次返回map_page的时候不至于总是resizeMap:
var refreshMap=true;
$(document).delegate('#map_page', 'pageshow', function () {
	curPage="map_page";
	if(refreshMap){
		refreshMap=false;		
		resizeMap();
	}
});


工具,计算2点间距离,返回的是mile英里数
function GetDistance(lat1,lng1,lat2,lng2){
   var radLat1 = Rad(lat1);
   var radLat2 = Rad(lat2);
   var a = radLat1 - radLat2;
   var  b = Rad(lng1) - Rad(lng2);
   var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
   Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
   s = s *6378.137 ;// EARTH_RADIUS;
   s = 0.62*Math.round(s * 10000) / 10000;
   s=s.toFixed(0);
   return s+"mi";
}


最后显示的效果如下:



  • 大小: 152.7 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics