谷歌地图API JS - 两个在一页之间的干扰?

时间:2015-07-15 13:57:29

标签: javascript twitter-bootstrap google-maps google-maps-api-3

我有一个包含多个不同视图的页面。在顶部有一个小的gogole地图用于搜索。其中一个视图有结果图。 站点在MVC 5 bootstrap 4中完成。

两者都在一起工作,但正如你所做的那样是添加/改变事物。现在他们不能很好地一起玩。

显示结果地图时 - 较小的搜索地图不会显示路线图。地图似乎已初步确定 - 但不显示道路/地图。如果我改为卫星 - 它似乎只显示在地图/帧的一部分内。我还注意到MapType控件已经从一个条形变为一个下拉菜单,这是较小屏幕的默认设置。

据我所知 - 机器人地图使用单独的变量。 最初不会在这里发布代码,因为这里有一点点 - 而且我认为如果有人之前经历过这样的行为,我会做一个初步的查询。 如果我禁用结果地图,搜索地图将再次运行。

在没有第二张地图的页面/视图上显示时更正搜索地图: search map showing ok

在页面/视图上显示第二个地图。注意更改地图类型控件: roads not showing, map type control changed

如果我改为显示卫星而不是道路 - 显示一部分。这在一定程度上是可行的,但部分会随之改变: Satellite showing to a certain extent

有什么想法吗? 可以自举发送不正确的屏幕尺寸信号吗? 如果认为它有用,可以发布代码。

澄清:

搜索地图定义。 注意HTML和JS包含一些前缀为" @"的ASP.Net MVC Razor代码。 此外,只有在窗口加载时打开Bootstrap面板时才会初始化地图。



< script >


  var markersSearch = [];
var mapSearch;



function ClearSearch() {
  //clear values + submmit form empty

  var form = document.getElementById("searchform");

  document.getElementById("Search").value = "";
  document.getElementById("eventtypeID").selectedIndex = 0;
  document.getElementById("EventFrom").value = "";
  document.getElementById("EventTo").value = "";
  document.getElementById("Free").checked = false;
  document.getElementById("hidLat").value = "";
  document.getElementById("hidLng").value = "";
  document.getElementById("distance").selectedIndex = 1;

  ClearLocations();

  form.submit();
}


function showsearch() {
  //show serch panel
  //only initialise map if not already done
  if (typeof mapSearch == 'undefined') {
    initializeSearch();
  }
}


function SetMyLocation() {




  //clear existing markers
  ClearLocations();
  //set to current pos

  if (navigator.geolocation) {

    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

      mapSearch.setCenter(initialLocation);


      // Create a marker for each place.
      var marker = new google.maps.Marker({
        map: mapSearch,
        //icon: image,
        title: 'My Location',
        position: initialLocation,
        draggable: true
      });

      //display
      markersSearch.push(marker);

      //zoom
      mapSearch.setZoom(16);

      //listener
      google.maps.event.addListener(marker, 'drag', function(event) {
        SetHtmlLocation(event.latLng.lat(), event.latLng.lng());
      });

      google.maps.event.addListener(marker, 'dragend', function(event) {
        SeHtmltLocation(event.latLng.lat(), event.latLng.lng());
      });

      SetHtmlLocation(position.coords.latitude, position.coords.longitude);

    });
  }

}

function SetLocation(lat, lng) {

    ClearLocations();
    var setLocation = new google.maps.LatLng(lat, lng);

    // Create a marker for each place.
    var markerSetLoc = new google.maps.Marker({
      map: mapSearch,
      //icon: image,
      title: 'My Location',
      position: setLocation,
      draggable: true
    });


    mapSearch.setCenter(setLocation);

    //zoom
    mapSearch.setZoom(16);

    //listener
    google.maps.event.addListener(markerSetLoc, 'drag', function(event) {
      SetHtmlLocation(event.latLng.lat(), event.latLng.lng());
    });

    google.maps.event.addListener(markerSetLoc, 'dragend', function(event) {
      SetHtmlLocation(event.latLng.lat(), event.latLng.lng());
    });


    //addd to array
    markersSearch.push(markerSetLoc);

    SetHtmlLocation(lat, lng);


  } //SetLocation

function SetHtmlLocation(lat, lng) {
  document.getElementById("hidLat").value = lat;
  document.getElementById("hidLng").value = lng;
}


function ClearLocationsIncInput() {
  document.getElementById("pac-input").value = '';
  ClearLocations();
}

function ClearLocations() {

  for (var i = 0; i < markersSearch.length; i++) {
    google.maps.event.clearInstanceListeners(markersSearch[i]);
    markersSearch[i].setMap(null);
  }
  markersSearch = [];

  SetHtmlLocation(null, null);

}

function initializeSearch() {


    //initialise starting point if form re-submited
    @
    if (!string.IsNullOrEmpty(ViewBag.currentLat)) {@: var londonLatLong = new google.maps.LatLng(@ViewBag.currentLat, @ViewBag.currentLng);@: var zoom = 16;
      //SetHtmlLocation done in control itself
    } else {@: var londonLatLong = new google.maps.LatLng(51.507, -0.1277);@: var zoom = 13;
    }



    var mapOptionsSearch = {
      center: londonLatLong,
      zoom: zoom,
      streetViewControl: false,
      zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL,
        position: google.maps.ControlPosition.RIGHT_BOTTOM
      },
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };




    mapSearch = new google.maps.Map(document.getElementById('event-map-search'), mapOptionsSearch);



    //IF ORIGINALLY PLACED - set marker on postback
    @
    if (!string.IsNullOrEmpty(ViewBag.currentLat)) {

      @: SetLocation(@ViewBag.currentLat, @ViewBag.currentLng);

    }



    // Create the search box and link it to the UI element.
    var input = /** @@type {HTMLInputElement} */ (
      document.getElementById('pac-input'));

    var inputgroup = (document.getElementById('pac-input-group'));

    //mapSearch.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
    mapSearch.controls[google.maps.ControlPosition.TOP_LEFT].push(inputgroup);

    var searchBox = new google.maps.places.SearchBox( /** @@type {HTMLInputElement} */ (input));


    // [START region_getplaces]
    // Listen for the event fired when the user selects an item from the
    // pick list. Retrieve the matching places for that item.
    google.maps.event.addListener(searchBox, 'places_changed', function() {


      var places = searchBox.getPlaces();

      if (places.length == 0) {
        return;
      }
      for (var i = 0, marker; marker = markersSearch[i]; i++) {
        marker.setMap(null);
      }

      // For each place, get the icon, place name, and location.
      ClearLocations();



      //use places[0]
      SetLocation(places[0].geometry.location.lat(), places[0].geometry.location.lng());


    });
    // [END region_getplaces]

    // Bias the SearchBox results towards places that are within the bounds of the
    // current map's viewport.
    google.maps.event.addListener(mapSearch, 'bounds_changed', function() {
      var boundsBias = mapSearch.getBounds();
      searchBox.setBounds(boundsBias);
    });


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

  } //initialize




$(function() {
  $('[data-toggle="tooltip"]').tooltip()
})







< /script>
&#13;
<style type="text/css"> #event-map-search {

  height: 100%;

  width: 100%;

  min-width: 200px;

  min-height: 200px;

  margin: 0;

  padding: 0;

}

.controls {

  margin-top: 16px;

  border: 1px solid transparent;

  border-radius: 2px 0 0 2px;

  box-sizing: border-box;

  -moz-box-sizing: border-box;

  height: 32px;

  outline: none;

  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);

}

/*Auto complete ?*/

#type-selector {

  color: #fff;

  background-color: #4d90fe;

  padding: 5px 11px 0px 11px;

}

#type-selector label {

  /*font-family: Roboto;*/

  font-size: 13px;

  font-weight: 300;

}

#pac-input {

  background-color: #fff;

  /*font-family: Roboto;*/

  /*font-size: 10px;*/

  font-weight: 300;

  width: 280px;

  /*padding: 0 11px 0 13px;*/

  text-overflow: ellipsis;

}

#pac-input-group {

  width: 300px;

  margin-top: 6px;

  margin-left: 6px;

}

#pac-input:focus {

  border-color: #4d90fe;

}

/*TODO - move to CSS*/

</style>
&#13;
<div id="pac-input-group" class="input-group">
  <input id="pac-input" class="form-control input-sm" type="text" placeholder="Choose a location">
  <span class="input-group-btn">
                                                        <button class="btn btn-default btn-sm" type="button" data-toggle="tooltip" data-placement="bottom" title="Set to my location" onclick="javascript: SetMyLocation();">
                                                            <span class="glyphicon glyphicon-record" aria-hidden="true"></span>
  </button>
  <button class="btn btn-default btn-sm" type="button" data-toggle="tooltip" data-placement="bottom" title="Clear Location" onclick="javascript: ClearLocationsIncInput();">
    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
  </button>
  </span>
</div>
<div id="event-map-search"></div>
@Html.Hidden("hidLat", (object)ViewBag.currentLat) @Html.Hidden("hidLng", (object)ViewBag.currentLng)
&#13;
&#13;
&#13;

显示地图的代码,在一个视图中包含为Razor / MVC:

Html.RenderPartial("EventsMap", Model);

&#13;
&#13;
< script type = "text/javascript" >

  var markersDisplay = [];
var mapDisplay;
var boundsDisplay = new google.maps.LatLngBounds();

function initializeDisplayMap() {



  @
  if (Model.Count > 0) {@: var firstPointDisplay = new google.maps.LatLng(@Model.FirstOrDefault().address_latitude, @Model.FirstOrDefault().address_longitude);
  } else {@: var firstPointDisplay = new google.maps.LatLng(51.507, -0.1277);
  }




  var mapOptionsDisplay = {
    zoom: 13,
    center: firstPointDisplay,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  mapDisplay = new google.maps.Map(document.getElementById('event-map-display'), mapOptionsDisplay);

  //draw marker code from C#
  @
  foreach(var item in Model) {@: addMarkerDisplay(@item.address_latitude, @item.address_longitude, '@Html.EncodeJsString(item.event_title)', @item.event_ID);

  }

  //collect all in bounds

  for (i = 0; i < markersDisplay.length; i++) {
    boundsDisplay.extend(markersDisplay[i].getPosition());
  }
  //bounds map
  mapDisplay.fitBounds(boundsDisplay);
}


function addMarkerDisplay(x, y, ptitle, eID) {

  var location = new google.maps.LatLng(x, y);
  var newmarkerDisplay = new google.maps.Marker({
    position: location,
    title: ptitle,
    map: mapDisplay,
    draggable: false,
    id: eID
  });

  markersDisplay.push(newmarkerDisplay);

  google.maps.event.addListener(newmarkerDisplay, 'click', function() {
    highlightevent(this.id);
  });

}

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



function highlightevent(id) {



  $('#eventMapTable tr').each(function() {
    //alert($(this).data('id'));
    $(this).removeClass("eventMapRowHighlight");
    if ($(this).data('id') == id) {
      $(this).addClass("eventMapRowHighlight");
    }
  });


}

< /script>
&#13;
/*---------------Events--------------------------*/

#event-map-display {

  height: 100%;

  width: 100%;

  min-width: 300px;

  min-height: 500px;

  margin: 0;

  padding: 0;

}

.eventTable tbody tr:hover td {

  background-color: black;

  color: white;

}

.eventTable tbody tr {

  cursor: pointer;

}

#EventListImageContainer {

  padding-top: 5px;

  height: 100%;

}

#EventMapContainer {

  padding-top: 5px;

  height: 100%;

}

#EventListImageContainer img {

  display: block;

  margin-left: auto;

  margin-right: auto;

}

.eventMapRowHighlight {

  background-color: @highlightcol1;

-webkit-transition: background 0.5s linear;

  -moz-transition: background 0.5s linear;

  -ms-transition: background 0.5s linear;

  -o-transition: background 0.5s linear;

  transition: background 0.5s linear;

}
&#13;
<div id="EventMapContainer" class="col-lg-5 col-md-5 col-sm-5 col-xs-12">
  <div id="event-map-display"></div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

修正了它。 :)

通过点击打开Boostrap面板所在位置的按钮来调用错误的地图初始化例程。 当页面没有包含另一张地图时,这一直在工作,但仍然有效。

以为我会检查一下在boostrap面板打开后触发的事件,因为它似乎与尺寸调整有关。

因此,我没有触发按钮onclick,而是实现了引导事件&#34; shown.bs.collapse&#34; :当一个折叠元素对用户可见时将触发此事件(将等待CSS转换完成)​​。

因此:

&#13;
&#13;
<!DOCTYPE html>
<html>
  <head>
    <!-- CSS  -->
    <script data-require="jquery@*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
    <link rel="stylesheet" href="style.css" />
    <!-- JS  -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="http://code.angularjs.org/1.2.13/angular.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.0/ui-bootstrap-tpls.js"></script>
    <script src="script.js"></script>
    <!-- // base path for angular routing   -->
    <!--<base href="/" />--> 
  </head>


<body ng-app="routerApp">


<!-- NAVIGATION -->

<!-- Fixed navbar -->
    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" ui-sref="home">Some web page somewhere</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li><a ui-sref="one">Link One</a></li>
            <li><a ui-sref="two">Link Two</a></li> 
            <li><a ui-sref="three">Link Three</a></li>
          </ul>

        </div><!--/.nav-collapse -->
      </div>
    </nav>
<!-- End Fixed navbar -->




<!-- MAIN CONTENT -->
<!--  Inject Content Here -->
<div class="container" style="padding-top:68px;">
    <div ui-view></div>
</div>





</body>
</html>
&#13;
&#13;
&#13;