GeoLocation Google Maps not working

守給你的承諾、 提交于 2019-12-13 08:44:31

问题


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


回答1:


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/




回答2:


I think you should include your Google Api key.

Try to add the script below :

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


来源:https://stackoverflow.com/questions/29829470/geolocation-google-maps-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!