GeoLocation Google地图无效 [英] GeoLocation Google Maps not working
问题描述
我试图在我的地图上获取范围环,图片的位置高于用户的位置,但是当我测试它时用户的位置似乎没有出现在地图上地图。我不知道出了什么问题,我在网站上跟着一个教程。
这是代码:
<!DOCTYPE html>< html> < HEAD> <标题>雷达< /标题> < meta http-equiv =refreshcontent =300> < meta charset =UTF-8> < meta name =viewportcontent =width = device-width,initial-scale = 1.0>< script type =text / javascriptsrc =http://maps.google.com/maps/ API / JS传感器=真>?< /脚本><风格> #map-canvas {height:700px; } #logo {position:fixed; z-index:99;上方:8%;剩下:3%;不透明度:0.9; } #legenda {position:absolute; z-index:98;顶部:87%;剩下:82%;不透明度:1.0; height:50px; }< / style> < /头> < body style =overflow:hidden;> < div id =map-canvas>< / div> < script src =http://code.jquery.com/jquery-latest.js>< / script> < script src =http://maps.googleapis.com/maps/api/js?sensor=false>< / script> < script type =text / javascript> // [START region_initialization] //此示例创建一个名为USGSOverlay的自定义覆盖图,其中包含//美国地质调查局(USGS)在地图上相关区域的图像。将自定义覆盖对象的原型设置为OverlayView的新实例。实际上,这将重叠覆盖类。//请注意,我们将原型设置为实例,而不是父类本身,因为我们不希望修改父类class.var覆盖; USGSOverlay.prototype = new google.maps.OverlayView(); //初始化地图和自定义overlay.function initialize(){if(navigator.geolocation){navigator.geolocation.getCurrentPosition(success);} else {error('Geo Location is not supported ');}函数成功(位置){var lat = position.coords.latitude; var long = position.coords.longitude;} var coords = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); var styles = [{featureType:administrative,elementType:geometry.fill,stylers:[{lightness:-88},{saturation:-100},{visibility :on}]},{featureType:administrative.country,stylers:[{visibility:on},{weight:1.3},{lightness:100}] },{featureType:landscape,stylers:[{saturation:-100},{lightness:-81}]},{featureType:poi,stylers {visibility:off}]},{featureType:road.local,stylers:[{visibility:off}]},{featureType:road.arterial ,elementType:geometry,stylers:[{visibility:off}]},{featureType:road.highway.controlled_access,stylers:[{visibility简化的}}},{featureType:road.highway.controlled_access,elementType:geometry.fill,stylers:[{visibility:simplified},{saturation 100},{lightness:100},{weight:1.3}]},{featureType:road.highway,stylers:[{visibility:simplified}]featureType:administrative.locality,elementType:labels,stylers:[{lightness:100},{visibility:simplified}]},{featureType:road .highway,elementType:geometry.fill,stylers:[{visibility:simplified},{lightness:100}],{featureType:administrative.province, elementType:geometry.stroke,stylers:[{lightness:100},{saturation:-100}]},{featureType:administrative.locality,elementType labels.icon,stylers:[{visibility:off}]},{featureType:road,elementType:geometry,stylers:[{lightness 65},{saturation:1},{hue:#0000ff}]},{featureType:water,stylers:[{saturation:-53},{ :-36},{hue:#00f6ff}]},{featureType:landscape,stylers:[{lightness:-39}]},{}] // Create一个新的StyledMapType对象,将它传递给样式数组//以及要在地图类型控件上显示的名称。 var styledMap = new google.maps.StyledMapType(styles,{name:Styled Map}); var mapOptions = {zoom:7,center:coords,panControl:false,zoomControl:false,mapTypeControl:false,streetViewControl:false,mapTypeIds:[google.maps.MapTypeId.ROADMAP,'map_style']}; var map = new google.maps.Map(document.getElementById(map-canvas),mapOptions); map.mapTypes.set('map_style',styleledMap); map.setMapTypeId('map_style'); var icon = {url:'met.nl.eu.org/klanten/python/marker.png'}; var marker = new google.maps.Marker({position:coords,map:map,icon:icon}); //在地图准备就绪后查询并绘制数据google.maps.event.addListenerOnce(map,'idle',function(){$ .ajax({dataType:json,url:http:// met。 (函数(闪电){var image ='http://met.nl.eu.org)。 /klanten/python/strike.png'new google.maps.Marker({position:new google.maps.LatLng(lightning.lat,lightning.lon),map:map,icon:image});});}) ;}); var swBound = new google.maps.LatLng(48.895311,0.000000); var neBound = new google.maps.LatLng(55.973607,10.856428); var bounds = new google.maps.LatLngBounds(swBound,neBound); //照片由MetNL提供。 var srcImage ='v2.0 / historie / 28-06-11 / 00.png'; //自定义USGSOverlay对象包含USGS图像,//图像的边界和对地图的引用。 overlay = new USGSOverlay(bounds,srcImage,map);} // [END region_initialization] // [START region_constructor] / ** @constructor * / function USGSOverlay(bounds,image,map){//初始化所有属性。 this.bounds_ = bounds; this.image_ = image; this.map_ = map; //定义一个属性来保存图像的div。我们会在接收到onAdd()//方法后创建这个div,所以我们现在将它保留为空。 this.div_ = null; //在这个覆盖层上显式调用setMap。 this.setMap(map);} // [END region_constructor] // [START region_attachment] / ** * onAdd在地图窗格准备就绪并且叠加层已添加到地图上时调用。 * / USGSOverlay.prototype.onAdd = function(){var div = document.createElement('div'); div.style.borderStyle ='none'; div.style.borderWidth ='0px'; div.style.position ='绝对'; //创建img元素并将其附加到div。 var img = document.createElement('img'); img.src = this.image_; img.style.width ='100%'; img.style.height ='100%'; img.style.position ='绝对'; div.appendChild(IMG); this.div_ = div; //将元素添加到overlayLayer窗格。 var panes = this.getPanes(); panes.overlayLayer.appendChild(div);}; // [END region_attachment] // [START region_drawing] USGSOverlay.prototype.draw = function(){//我们使用坐标的西南和东北重叠以将其固定到正确的位置和大小。 //为此,我们需要从叠加层中检索投影。 var overlayProjection = this.getProjection(); //在LatLng中检索此叠加层的西南和东北坐标//并将其转换为像素坐标。 //我们将使用这些坐标来调整div的大小。 var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest()); var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast()); //调整图片div的大小以适应指定的尺寸。 var div = this.div_; div.style.left = sw.x +'px'; div.style.top = ne.y +'px'; div.style.width =(ne.x - sw.x)+'px'; div.style.height =(sw.y - ne.y)+'px';}; // [END region_drawing] // [START region_removal] //从API自动调用onRemove()方法if / /我们曾经设置overlay的map属性为'null'.USGSOverlay.prototype.onRemove = function(){this.div_.parentNode.removeChild(this.div_); this.div_ = null;}; // [END region_removal] google.maps.event.addDomListener(window,'load',initialize); < /脚本> < img src =http://met.nl.eu.org/NL_nl/iframe/logo.pngid =logo/> < img src =http://met.nl.eu.org/klanten/python/legenda.pngid =legenda/> < / body>< / html>
用我的代码?
**编辑:Ik现在知道故障发生在这部分代码中:var coords = new google.maps.LatLng(position.coords。纬度,position.coords.longitude);
它提供了一个参考错误,说位置没有定义,而在我写的代码的早些时候:函数成功(位置){
var lat = position.coords.latitude;
var long = position.coords.longitude;
}
您地理位置异步运行。
可以在返回结果时创建地图/标记,或者在返回结果时定义默认坐标并更新地图/标记。第二种方法更可取,因为当地理定位失败时,你根本不会得到一张地图。
一个使用MVCObject的简单实现,它可以很容易地访问该值并且观察更改(我已经删除了不相关的部分):
函数initialize(){
//定义一个默认位置
var coords = new google.maps.MVCObject();
coords.set('latlng',new google.maps.LatLng(52.370215,4.895167));
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(success);
//为坐标设置新值
函数成功(位置){
coords.set('latlng',
新的google.maps.LatLng(position.coords.latitude,
position.coords.longitude));
}
var mapOptions = {
zoom:7,
center:coords.get('latlng')
};
var map = new google.maps.Map(document.getElementById(map-canvas),
mapOptions);
var marker = new google.maps.Marker({
position:coords.get('latlng'),
map:map
});
//观察coords的latlng属性,
//更新标记和地图中心,当它更改时
google.maps.event.addListenerOnce(coords,'latlng_changed ',function(){
var latlng = this.get('latlng');
map.setCenter(latlng);
marker.setPosition(latlng)
});
}
google.maps.event.addDomListener(window,'load',initialize);
演示: http://jsfiddle.net/doktormolle/rttvLsLs/
I'm trying to get range-rings on my map, with the position of the image above the user's location, but the map doesn't appear when I test it and the user's location doesn't seem to show up on the map. I don't know what went wrong, I followed a tutorial on a website. This is the code:
<!DOCTYPE html>
<html>
<head>
<title>Radar</title>
<meta http-equiv="refresh" content="300">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<style>
#map-canvas {
height: 700px;
}
#logo {
position: fixed;
z-index: 99;
top: 8%;
left: 3%;
opacity: 0.9;
}
#legenda {
position: absolute;
z-index: 98;
top: 87%;
left: 82%;
opacity: 1.0;
height: 50px;
}
</style>
</head>
<body style="overflow: hidden;">
<div id="map-canvas"></div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
// [START region_initialization]
// This example creates a custom overlay called USGSOverlay, containing
// a U.S. Geological Survey (USGS) image of the relevant area on the map.
// Set the custom overlay object's prototype to a new instance
// of OverlayView. In effect, this will subclass the overlay class.
// Note that we set the prototype to an instance, rather than the
// parent class itself, because we do not wish to modify the parent class.
var overlay;
USGSOverlay.prototype = new google.maps.OverlayView();
// Initialize the map and the custom overlay.
function initialize() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
function success(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
}
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var styles =
[ { "featureType": "administrative", "elementType": "geometry.fill", "stylers": [ { "lightness": -88 }, { "saturation": -100 }, { "visibility": "on" } ] },{ "featureType": "administrative.country", "stylers": [ { "visibility": "on" }, { "weight": 1.3 }, { "lightness": 100 } ] },{ "featureType": "landscape", "stylers": [ { "saturation": -100 }, { "lightness": -81 } ] },{ "featureType": "poi", "stylers": [ { "visibility": "off" } ] },{ "featureType": "road.local", "stylers": [ { "visibility": "off" } ] },{ "featureType": "road.arterial", "elementType": "geometry", "stylers": [ { "visibility": "off" } ] },{ "featureType": "road.highway.controlled_access", "stylers": [ { "visibility": "simplified" } ] },{ "featureType": "road.highway.controlled_access", "elementType": "geometry.fill", "stylers": [ { "visibility": "simplified" }, { "saturation": -100 }, { "lightness": 100 }, { "weight": 1.3 } ] },{ "featureType": "road.highway", "stylers": [ { "visibility": "simplified" } ] },{ "featureType": "administrative.locality", "elementType": "labels", "stylers": [ { "lightness": 100 }, { "visibility": "simplified" } ] },{ "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [ { "visibility": "simplified" }, { "lightness": 100 } ] },{ "featureType": "administrative.province", "elementType": "geometry.stroke", "stylers": [ { "lightness": 100 }, { "saturation": -100 } ] },{ "featureType": "administrative.locality", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] },{ "featureType": "road", "elementType": "geometry", "stylers": [ { "lightness": -65 }, { "saturation": 1 }, { "hue": "#0000ff" } ] },{ "featureType": "water", "stylers": [ { "saturation": -53 }, { "lightness": -36 }, { "hue": "#00f6ff" } ] },{ "featureType": "landscape", "stylers": [ { "lightness": -39 } ] },{ } ]
// Create a new StyledMapType object, passing it the array of styles,
// as well as the name to be displayed on the map type control.
var styledMap = new google.maps.StyledMapType(styles,
{name: "Styled Map"});
var mapOptions = {
zoom: 7,
center: coords,
panControl: false,
zoomControl: false,
mapTypeControl: false,
streetViewControl: false,
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
var icon = {
url: 'met.nl.eu.org/klanten/python/marker.png'
};
var marker = new google.maps.Marker({
position: coords,
map: map,
icon: icon
});
// Query and plot the data once the map is ready
google.maps.event.addListenerOnce(map, 'idle', function() {
$.ajax({
dataType: "json",
url: "http://met.nl.eu.org/klanten/python/get_lightnings.php"
}).done(function(data) {
data.d.forEach(function(lightning) {
var image = 'http://met.nl.eu.org/klanten/python/strike.png'
new google.maps.Marker({
position: new google.maps.LatLng(lightning.lat, lightning.lon),
map: map,
icon: image });
});
});
});
var swBound = new google.maps.LatLng(48.895311, 0.000000);
var neBound = new google.maps.LatLng(55.973607, 10.856428);
var bounds = new google.maps.LatLngBounds(swBound, neBound);
// The photograph is courtesy of MetNL.
var srcImage = 'v2.0/historie/28-06-11/00.png';
// The custom USGSOverlay object contains the USGS image,
// the bounds of the image, and a reference to the map.
overlay = new USGSOverlay(bounds, srcImage, map);
}
// [END region_initialization]
// [START region_constructor]
/** @constructor */
function USGSOverlay(bounds, image, map) {
// Initialize all properties.
this.bounds_ = bounds;
this.image_ = image;
this.map_ = map;
// Define a property to hold the image's div. We'll
// actually create this div upon receipt of the onAdd()
// method so we'll leave it null for now.
this.div_ = null;
// Explicitly call setMap on this overlay.
this.setMap(map);
}
// [END region_constructor]
// [START region_attachment]
/**
* onAdd is called when the map's panes are ready and the overlay has been
* added to the map.
*/
USGSOverlay.prototype.onAdd = function() {
var div = document.createElement('div');
div.style.borderStyle = 'none';
div.style.borderWidth = '0px';
div.style.position = 'absolute';
// Create the img element and attach it to the div.
var img = document.createElement('img');
img.src = this.image_;
img.style.width = '100%';
img.style.height = '100%';
img.style.position = 'absolute';
div.appendChild(img);
this.div_ = div;
// Add the element to the "overlayLayer" pane.
var panes = this.getPanes();
panes.overlayLayer.appendChild(div);
};
// [END region_attachment]
// [START region_drawing]
USGSOverlay.prototype.draw = function() {
// We use the south-west and north-east
// coordinates of the overlay to peg it to the correct position and size.
// To do this, we need to retrieve the projection from the overlay.
var overlayProjection = this.getProjection();
// Retrieve the south-west and north-east coordinates of this overlay
// in LatLngs and convert them to pixel coordinates.
// We'll use these coordinates to resize the div.
var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());
// Resize the image's div to fit the indicated dimensions.
var div = this.div_;
div.style.left = sw.x + 'px';
div.style.top = ne.y + 'px';
div.style.width = (ne.x - sw.x) + 'px';
div.style.height = (sw.y - ne.y) + 'px';
};
// [END region_drawing]
// [START region_removal]
// The onRemove() method will be called automatically from the API if
// we ever set the overlay's map property to 'null'.
USGSOverlay.prototype.onRemove = function() {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
};
// [END region_removal]
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<img src="http://met.nl.eu.org/NL_nl/iframe/logo.png" id="logo"/>
<img src="http://met.nl.eu.org/klanten/python/legenda.png" id="legenda"/>
</body>
</html>
Wat went wrong with my code?
**Edit: Ik now know the fault occurs in this portion of the code: var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); It gives a reference error saying "position is not defined" while earlier in the code i've written this: function success(position) { var lat = position.coords.latitude; var long = position.coords.longitude; }
geolocation runs asynchronously.
You may either create the map/marker when it returns a result or define a default-coordinate and update map/marker when it returns a result.
The 2nd approach is preferable, because you wouldn't get a map at all when geolocation fails.
A simple implementation using a MVCObject, which makes it easy to 1. access the value and 2. observe changes(I've removed the irrelevant parts):
function initialize() {
//define a default-position
var coords = new google.maps.MVCObject();
coords.set('latlng', new google.maps.LatLng(52.370215, 4.895167));
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
}
//set new value for coords
function success(position) {
coords.set('latlng',
new google.maps.LatLng(position.coords.latitude,
position.coords.longitude));
}
var mapOptions = {
zoom: 7,
center: coords.get('latlng')
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var marker = new google.maps.Marker({
position: coords.get('latlng'),
map: map
});
//observe the latlng-property of coords,
//and update marker and map-center when it changes
google.maps.event.addListenerOnce(coords, 'latlng_changed', function () {
var latlng = this.get('latlng');
map.setCenter(latlng);
marker.setPosition(latlng)
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Demo: http://jsfiddle.net/doktormolle/rttvLsLs/
这篇关于GeoLocation Google地图无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!