GeoLocation Google地图不起作用

时间:2015-04-23 16:34:00

标签: javascript google-maps google-maps-api-3 geolocation

我试图在我的地图上获得范围响铃,图像的位置在用户的位置上方,但是当我测试它并且用户&#时,地图不会出现39;位置似乎没有显示在地图上。我不知道出了什么问题,我在网站上关注了教程。 这是代码:



<!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>
&#13;
&#13;
&#13;

Wat我的代码出了问题?

**编辑:我现在知道代码的这一部分出现了错误:var coords = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); 它给出了一个参考错误,说&#34;位置未定义&#34;虽然在代码的前面我写过:功能成功(位置){      var lat = position.coords.latitude;      var long = position.coords.longitude; }

2 个答案:

答案 0 :(得分:1)

地理定位以异步方式运行。

您可以在返回结果时创建地图/标记,也可以在返回结果时定义默认坐标并更新地图/标记。

第二种方法更可取,因为地理位置失败时根本不会得到地图。

使用MVCObject的一个简单实现,它可以很容易地1.访问值和2.观察更改(我删除了不相关的部分):

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);

演示:http://jsfiddle.net/doktormolle/rttvLsLs/

答案 1 :(得分:0)

我认为您应该包含Google Api密钥。

尝试添加以下脚本:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
type="text/javascript"></script>