Javascript 将文本搜索添加到我的谷歌地图脚本
我想将textSearch添加到我的脚本中,但当我添加它时,地图不会显示,以下是我的主脚本:Javascript 将文本搜索添加到我的谷歌地图脚本,javascript,google-maps,google-maps-api-3,Javascript,Google Maps,Google Maps Api 3,我想将textSearch添加到我的脚本中,但当我添加它时,地图不会显示,以下是我的主脚本: <script src="http://maps.google.com/maps/api/js?sensor=true"></script> <script> function writeAddressName(latLng) { var geocoder = new google.maps.Geocoder(); geocoder.geocode
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script>
function writeAddressName(latLng) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": latLng
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
document.getElementById("address").innerHTML = results[0].formatted_address;
else
document.getElementById("error").innerHTML += "Unable to retrieve your address" + "<br />";
});
}
function geolocationSuccess(position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Write the formatted address
writeAddressName(userLatLng);
var myOptions = {
center : userLatLng,
zoom : 10,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
// Place the marker
new google.maps.Marker({
map: mapObject,
position: userLatLng
});
// Draw a circle around the user position to have an idea of the current localization accuracy
var circle = new google.maps.Circle({
center: userLatLng,
radius: 800,
map: mapObject,
fillColor: '#FFF32F',
fillOpacity: 0.5,
strokeColor: '#F1E401',
strokeOpacity: 1.0
});
mapObject.fitBounds(circle.getBounds());
}
function geolocationError(positionError) {
document.getElementById("error").innerHTML += "Error: " + positionError.message + "<br />";
}
function geolocateUser() {
// If the browser supports the Geolocation API
if (navigator.geolocation)
{
var positionOptions = {
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
};
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError, positionOptions);
}
else
document.getElementById("error").innerHTML += "Your browser doesn't support the Geolocation API";
}
window.onload = geolocateUser;
</script>
但仍然无法在地图中找到位置,我正在尝试的是定位某人,然后在该位置添加一个圆圈,并显示周围的药店…我认为您可能无法在HTML或CSS文件中正确设置地图样式。此外,还需要在任何函数之外声明mapObject变量 我为您的地图设置以下样式:
<style>
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
您还需要包含GoogleMapsV3脚本来渲染地图
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
然后,我用JSFIDLE中的一些HTML和CSS代码尝试了您的代码,它显示了一个带有圆圈的地图。获取用户位置并加载地图需要几秒钟:
需要注意的是,您在函数中声明和设置map变量,但在其他函数中需要它。因此,在writeAddressName函数声明上方的新行中将其声明为全局变量。So-var映射;但仍然无法获得地图:s@mindparse
<style>
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>