【问题标题】:google maps API v3 - zoom after load Howgoogle maps API v3 - 加载后缩放如何
【发布时间】:2013-06-27 11:53:56
【问题描述】:

我正在尝试加载谷歌地图,然后放大我的标记,但我的 javascript 有问题,因为地图的范围是不可见的,尽管它是全局定义的。

任何想法我做错了什么?

非常感谢

标记

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <script src="js/jquery-1.10.1.min.js"></script>    
    <link href="css/default.css" rel="stylesheet">
    <!--
    Include the maps javascript with sensor=true because this code is using a
    sensor (a GPS locator) to determine the user's location.
    See: https://developers.google.com/apis/maps/documentation/javascript/basics#SpecifyingSensor
    -->
    <script src="https://maps.googleapis.com/maps/api/js?v=3.12&sensor=true"></script>

    <script>

//START Global Variables
var geocoder;
var map;
var marker;
var initialZoomLevel = 7;
var endZoomLevel = 16;
var zoomTimeInterval_ms = 1000;
var mapIcon = {
  url: "images/im_here.png",
   // This marker is 130 pixels wide by 120 pixels tall
  size: new google.maps.Size(130,120),
  //scale image so it works with retina displays
  scaledSize: new google.maps.Size(65,60),
  // The origin for this image is 0,0.
  origin: new google.maps.Point(0,0),  
  // The anchor point is be middle of the base
  anchor: new google.maps.Point(32.5,60)
};
var mapIcon_shadow = {
  url: "images/im_here_shadow.png",
   // This shadow is 191 pixels wide by 120 pixels tall
  size: new google.maps.Size(191,120),
  //scale image so it works with retina displays
  scaledSize: new google.maps.Size(95.5,60),
  // The origin for this image is 0,0.
  origin: new google.maps.Point(0,0),  
  // The anchor point is be middle of the base
  anchor: new google.maps.Point(32.5,60)
};
//Enable the visual refresh
google.maps.visualRefresh = true;
//END Global Variables

/** Initialise function to render the map */
function initialize() {
  geocoder = new google.maps.Geocoder();
  var mapOptions = {
    zoom: initialZoomLevel,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: false,
    panControl: false,
    streetViewControl: false,
    zoomControl: false
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  // Try HTML5 geolocation
  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var pos = new google.maps.LatLng(position.coords.latitude,
                                       position.coords.longitude);

      // set home location
      home = new google.maps.LatLng(position.coords.latitude,
                                    position.coords.longitude);

      // the marker where you are
      marker = new google.maps.Marker({
        map: map,
        position: pos,
        icon: mapIcon,
        shadow: mapIcon_shadow,
        draggable: true
      });

      codeLatLng(pos);
      map.panTo(pos);

      google.maps.event.addListener(marker, 'dragend', function(a) {
        //alert('LatLng is '+a.latLng.lat()+ " "+ a.latLng.lng());
        codeLatLng(a.latLng);
      });

    }, function() {
      handleNoGeolocation(true);
    });
  } else {
    // Browser doesn't support Geolocation
    handleNoGeolocation(false);
  }

  // Create the DIV to hold the control and
  // call the HomeControl() constructor passing
  // in this DIV.
  //var homeControlDiv = document.createElement('div');
  //var homeControl = new HomeControl(homeControlDiv, map);

  //homeControlDiv.index = 1;
  //map.controls[google.maps.ControlPosition.TOP_CENTER].push(homeControlDiv);  

  smoothZoom(map, endZoomLevel, map.getZoom()); // call smoothZoom, parameters map, final zoomLevel, and starting zoom level  
}

function handleNoGeolocation(errorFlag) {
  if (errorFlag) {
    var content = 'Error: The Geolocation service failed.';
  } else {
    var content = 'Error: Your browser doesn\'t support geolocation.';
  }

  var options = {
    map: map,
    position: new google.maps.LatLng(60, 105),
    content: content
  };

  var infowindow = new google.maps.InfoWindow(options);
  map.setCenter(options.position);
}

function codeLatLng(markerLatLang) {
  //var latlng = new google.maps.LatLng(latLng.lat(), latLng.lng());
  geocoder.geocode({'latLng': markerLatLang}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[0]) {
        name = results[0].formatted_address;
        latlongStr = "LAT = ["+markerLatLang.lat()+"] LNG = ["+markerLatLang.lng()+"]";
        //alert("name = "+name);      
        $('#address').html(name);
        $('#latlong').html(latlongStr);
      } else {
        alert('No results found');
      }
    } else {
      alert('Geocoder failed due to: ' + status);
    }
  });
}

/**
 * The HomeControl adds a control to the map that simply
 * returns the user to home. This constructor takes
 * the control DIV as an argument.
 * @constructor
 */
 /** TODO need to rewite this as normal div, not on map **/
function HomeControl(controlDiv, map) {

  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map
  controlDiv.style.padding = '5px';

  // Set CSS for the control border
  var controlUI = document.createElement('div');
  controlUI.style.backgroundColor = 'white';
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderWidth = '2px';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Click to set the map to Start Location';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior
  var controlText = document.createElement('div');
  controlText.style.fontFamily = 'Helvetica,sans-serif';
  controlText.style.fontSize = '16px';
  controlText.style.paddingLeft = '4px';
  controlText.style.paddingRight = '4px';
  controlText.style.zIndex = "100";
  controlText.innerHTML = '<b>Reset Map</b>';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map back to home
  google.maps.event.addDomListener(controlUI, 'click', function() {
    marker.setPosition(home);
    map.setCenter(home);
  });
}

// the smooth zoom function
function smoothZoom (map, max, cnt) {
    if (cnt >= max) {
            return;
        }
    else {
        z = google.maps.event.addListener(map, 'zoom_changed', function(event){
            google.maps.event.removeListener(z);
            self.smoothZoom(map, max, cnt + 1);
        });
        setTimeout(function(){map.setZoom(cnt)}, zoomTimeInterval_ms);
    }
}  

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="panel">        
        <div id="latlong">No latlong Yet</div>
        <div id="address">No Address Yet</div>
    </div>
    <div id="map-canvas"></div>
  </body>
</html>

【问题讨论】:

    标签: google-maps-api-3


    【解决方案1】:

    如果您不等到它被初始化后再使用它,那么您的地图是全局定义的这一事实是不相关的。 它由在主体 onload 事件上运行的初始化函数初始化。在此之前,您可以内联使用它。这对我有用:

    function initialize() {
      geocoder = new google.maps.Geocoder();
      var mapOptions = {
        zoom: initialZoomLevel,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        panControl: false,
        streetViewControl: false,
        zoomControl: false
      };
      map = new google.maps.Map(document.getElementById('map-canvas'),
          mapOptions);
    
      google.maps.event.addListenerOnce(map,"zoom_changed", function() {
         smoothZoom(map, endZoomLevel, map.getZoom()); // call smoothZoom, parameters map, final zoomLevel, and starting zoom level
      });   
    

    working example

    似乎在地图初始化时 zoom_changed 事件不会触发,使用“idle”事件似乎有效: working example with zoom on idle

    【讨论】:

    • 您好 geocodezip,感谢您的回复,好的,我现在明白为什么会出现错误,正如您所说,我必须等待 body onload 事件来初始化它。但是缩放不起作用,即使在您的示例中,它也保持在初始级别(在 FF 和 Chrome 上)我希望加载地图然后它会自动放大标记。非常感谢
    • 感谢 geocodezip cmets,我现在几乎可以使用它了。我已经更新了原始代码,它现在可以缩放,但它没有正确刷新地图。即在某些缩放级别上,它是一张空白地图,知道如何在每个缩放级别强制刷新地图吗?谢谢
    • 我面临同样的问题。我不确定缩放选项是否有效,但肯定不会在视觉上令人耳目一新。我看不到它被放大了。但它工作的 HTML 版本 geocodezip.com/GMapsExampleV3b.html
    • 我相信这个问题在某种程度上与初始化()有关,它会在正文加载时触发!
    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 2011-01-27
    • 1970-01-01
    相关资源
    最近更新 更多