Google地图--实现自动搜索地址和点击获取地图经纬度

一、实现效果

1、在搜索框输入地址,自动出现可定位地址选择
2、搜索地址后,刷新地图标注
3、点击地图其他区域,显示经纬度和点击的地址

tips:申请google api秘钥参考博客:https://blog.csdn.net/Ariel_201311/article/details/94441085

二、HTML

<div class="r-inputs">
	<div>
		经度:<input type="" name="" id="address_lng" value="经度" /> 
		纬度:<input type="" name="" id="address_lat" value="纬度" />
	div>
	地址:<input type="" name="" id="address" value="address" class="r-address" />
div>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map" style="width:800px; height:750px">div>

<script src="js/jquery.min.js">script>
//需要获取google地图的api_key
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete" async defer>script>

三、JS

var lngtxt = "101.686855";
var lattxt = "3.139003";
var addresstxt = "吉隆坡";

var map;
var marker;
var infowindow;
var geocoder;
var markersArray = [];

function initAutocomplete() {
	var latlng = new google.maps.LatLng(lattxt, lngtxt);
	var myOptions = {
		zoom: 13,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById('map'), myOptions);
	
	geocoder = new google.maps.Geocoder(); //实例化地址解析
	//监听点击地图事件
	google.maps.event.addListener(map, 'click', function(event) {
		placeMarker(event.latLng);
	});
	// Create the search box and link it to the UI element.
	var input = document.getElementById('pac-input');
	var searchBox = new google.maps.places.SearchBox(input);
	map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

	// Bias the SearchBox results towards current map's viewport.
	map.addListener('bounds_changed', function() {
		searchBox.setBounds(map.getBounds());
	});

	var markers = [];
	// Listen for the event fired when the user selects a prediction and retrieve
	// more details for that place.
	searchBox.addListener('places_changed', function() {
		var places = searchBox.getPlaces();

		if(places.length == 0) {
			return;
		}

		// Clear out the old markers.
		markers.forEach(function(marker) {
			marker.setMap(null);
		});
		markers = [];

		// For each place, get the icon, name and location.
		var bounds = new google.maps.LatLngBounds();
		places.forEach(function(place) {
			if(!place.geometry) {
				console.log("Returned place contains no geometry");
				return;
			}
			var icon = {
				url: place.icon,
				size: new google.maps.Size(71, 71),
				origin: new google.maps.Point(0, 0),
				anchor: new google.maps.Point(17, 34),
				scaledSize: new google.maps.Size(25, 25)
			};
			//console.log(place.geometry.location.lat());
			mapClick(place.geometry.location.lng(), place.geometry.location.lat(), place.name);
			// Create a marker for each place.
			markers.push(new google.maps.Marker({
				map: map,
				icon: icon,
				title: place.name,
				position: place.geometry.location
			}));

			if(place.geometry.viewport) {
				// Only geocodes have viewport.
				bounds.union(place.geometry.viewport);
			} else {
				bounds.extend(place.geometry.location);
			}
		});
		map.fitBounds(bounds);
	});
}

function placeMarker(location) {
	clearOverlays(infowindow); //清除地图中的标记
	marker = new google.maps.Marker({
		position: location,
		map: map
	});
	markersArray.push(marker);
	//根据经纬度获取地址
	if(geocoder) {
		geocoder.geocode({
			'location': location
		}, function(results, status) {
			if(status == google.maps.GeocoderStatus.OK) {
				if(results[0]) {
					attachSecretMessage(marker, results[0].geometry.location, results[0].formatted_address);
				}
			} else {
				alert("Geocoder failed due to: " + status);
			}
		});
	}
}
//在地图上显示经纬度地址
function attachSecretMessage(marker, piont, address) {
	var message = "坐标:" + piont.lat() + " , " + piont.lng() + "
"
+ "地址:" + address; var infowindow = new google.maps.InfoWindow({ content: message, size: new google.maps.Size(50, 50) }); infowindow.open(map, marker); if(typeof(mapClick) == "function") mapClick(piont.lng(), piont.lat(), address); } //删除所有标记阵列中消除对它们的引用 function clearOverlays(infowindow) { if(markersArray && markersArray.length > 0) { for(var i = 0; i < markersArray.length; i++) { markersArray[i].setMap(null); } markersArray.length = 0; } if(infowindow) { infowindow.close(); } } function setiInit() { // 页面加载显示默认lng lat address---begin if(lattxt != '' && lngtxt != '' && addresstxt != '') { var latlng = new google.maps.LatLng(lattxt, lngtxt); marker = new google.maps.Marker({ position: latlng, map: map }); markersArray.push(marker); attachSecretMessage(marker, latlng, addresstxt); } } function mapClick(lng, lat, address) { window.parent.document.getElementById("address_lng").value = lng; window.parent.document.getElementById("address_lat").value = lat; window.parent.document.getElementById("address").value = address; } window.onload = function() { setiInit(); }

四、CSS

html,
body {
	height: 100%;
	margin: 20px;
	padding: 0;
}

.controls {
	margin-top: 10px;
	border: 1px solid transparent;
	border-radius: 2px 0 0 2px;
	box-sizing: border-box;
	-moz-box-sizing: border-box;
	height: 32px;
	outline: none;
	box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

#pac-input {
	background-color: #fff;
	font-family: Roboto;
	font-size: 15px;
	font-weight: 300;
	margin-left: 12px;
	padding: 0 11px 0 13px;
	text-overflow: ellipsis;
	width: 280px;
	margin-top: 16px;
	height: 30px;
}

#pac-input:focus {
	border-color: #4d90fe;
}

.pac-container {
	font-family: Roboto;
}

#type-selector {
	color: #fff;
	background-color: #4d90fe;
	padding: 5px 11px 0px 11px;
}

#type-selector label {
	font-family: Roboto;
	font-size: 13px;
	font-weight: 300;
}

#target {
	width: 345px;
}

.line {
	display: flex;
	justify-content: flex-start;
	align-items: center;
}

.inputCnt {
	width: 200px;
	height: 30px;
	margin: 0 10px;
}

.btn1 {
	height: 36px;
}

.inputCnt2 {
	width: 100px;
	height: 30px;
	margin: 0 10px;
}

.r-inputs {}

.r-inputs input {
	height: 30px;
	padding-left: 8px;
}

.r-inputs>div {
	display: flex;
	align-items: baseline;
}

.r-inputs>div input {
	margin: 0 10px 10px 0;
}

.r-inputs input.r-address {
	margin-bottom: 10px;
	width: 400px;
}

五、google api启用

在申请google地图账号时,有多个api可供选择,但是这些api需要手动去启用才有效,这个demo需要启用的api为:

Geolocation API
Maps JavaScript API
Geocoding API
Places API

六、效果显示

你可能感兴趣的:(google,地图,获取地图经纬度,google,地图,api,地图)