Несколько мест на карте Google - PullRequest
2 голосов
/ 04 января 2011

Как я могу показать несколько мест на карте Google.Я использую этот код для карты Google?

<script type="text/javascript">
          $(function() { // when the document is ready to be manipulated.

              if (GBrowserIsCompatible()) { // if the browser is compatible with Google Map's
                  var map = document.getElementById("myMap"); // Get div element
                  var m = new GMap2(map); // new instance of the GMap2 class and pass in our div location.

                  var longArray= ("<?php echo $long; ?>").split(',');
                  var latArray= ("<?php echo $lat; ?>").split(',');

                 for(i=0;i<longArray.length;i++)
                 {
                     m.setCenter(new GLatLng(latArray[i], longArray[i]), 13); // pass in latitude, longitude, and zoom level.
                     m.openInfoWindow(m.getCenter(), document.createTextNode("This is testing")); // displays the text

                 }

                m.setMapType(G_SATELLITE_MAP); // sets the default mode. G_NORMAL_MAP, G_HYBRID_MAP

                    var c = new GMapTypeControl(); // switch map modes
                    m.addControl(c);

                    m.addControl(new GLargeMapControl()); // creates the zoom feature


              }
              else {
                  alert("Upgrade your browser, man!");
              }
          });
      </script>

Ответы [ 3 ]

2 голосов
/ 11 апреля 2019

См. Ниже код, который работал отлично для меня. Приведенный ниже фрагмент кода даст вам ошибку при предоставлении действительного ключа API, т. Е. «Ошибка API JavaScript Карт Google: InvalidKeyMapError», для решения этой проблемы единственное, что вам нужно, это действительный ключ API, предоставленный картами Google.

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Multiple Locations using Google Maps </title>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=false"></script>
</head>
<body>
    <div id="googleMap" style="width: 500px; height: 400px;"></div>

    <script type="text/javascript">
    var locationArray = [
      ['Pune', 18.5248904, 73.7228789, 1],
      ['Mumbai', 19.0825223, 72.7410977, 2],
      ['Ahmednagar', 19.1104918, 74.6728675, 3],
      ['Surat', 21.1594627, 77.3507354, 4],
      ['Indore', 22.7242284, 75.7237617, 5]
    ];

    var map = new google.maps.Map(document.getElementById('googleMap'), {
      zoom: 8,
      center: new google.maps.LatLng(18.5248904,73.7228789),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locationArray.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locationArray[i][1], locationArray[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locationArray[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
    </script>
</body>
</html>

Подробнее см. здесь . Я надеюсь, что это то, что вы ищете!

1 голос
/ 07 января 2011

setCenter используется для масштабирования и центрирования карты. Если вы хотите отметить несколько мест, вам нужно создать маркер и поместить его на карту внутри цикла. Здесь есть хороший набор учебных пособий:

http://econym.org.uk/gmap/index.htm

Если ваш вопрос связан с отображением нескольких людей разнородных местоположений на одной карте, то вы не можете, карта может быть центрирована только по одному широте / долготе за раз.

Не совсем ясно, чего вы пытаетесь достичь.

Dunc.

0 голосов
/ 08 февраля 2013

следующих шагов вы должны следовать.1. составьте список ваших адресов в javascript aaray.2. сделать функцию полезности для геокодирования, а затем поставить маркер, передавая адрес в качестве аргумента.3. переберите массив адресов и вызовите функцию маркера.

пример: map.jsp :: он сообщает входную строку json, которая является списком адресов, и преобразует ее в массив javascript: добавьте jquery и infobox.js, загрузив gron google.

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
   <%@ page contentType="text/html;charset=windows-1252"%>
     <html> 
    <head> 
       <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
        <title>Google Maps Multiple Markers</title> 
     <script src="http://maps.google.com/maps/api/js?sensor=false" 
      type="text/javascript"></script>
         <script language="JavaScript" src="js/jquery-1.8.0.min.js"       type="text/javascript"></script>
      <script language="JavaScript" src="js/infobox.js" type="text/javascript"></script>

     </head> 
   <body>
   <%
       String json=request.getParameter("address");
    %>
       <input type="hidden" id="json" value="<%=json%>"></input>

       <div id="map" style="width: 1250px; height: 500px;" align="center"></div>

         <script type="text/javascript" language="JavaScript" src="js/map.js"></script>
          <script type="text/javascript">
            var jsonvalue=document.getElementById("json").value;
         var use=unescape(jsonvalue);
       //alert(use);
              var obj = eval ("(" + use + ")"); 
    var cobj=obj.center;
       var olist=obj.other;
     codeproject(cobj.center_add,cobj.center_name);
      //alert(cobj.center_name+" and "+cobj.center_add);
     for(var i=0;i<olist.length;i++)
     {
     //alert(olist[i].other_add);
     codeAddress(olist[i].other_add,olist[i].other_name);
     }

      </script>
     </body>
     </html>

__ _ __ _ __ map.js _ __ _ __ _ _

       //used by infowindow
        //the googlemap code
   var geocoder = new google.maps.Geocoder();
  //var infowindow = new google.maps.InfoWindow();
   var LatLngList = new Array(6);
    var  i;
        var infowindow = new google.maps.InfoWindow();

     var markerBounds = new google.maps.LatLngBounds();
       var markerarray=new Array();
         //making the div for window popup
    var boxText = document.createElement("div");
        boxText.style.cssText = "border: 2px solid Gray; margin-top: 6px;       background:           white; padding: 5px;font-weight: bold;color: Gray;";
    boxText.innerHTML = " ";

    //options array for infobox window
     var myOptions = {
       map:map,
         content : boxText,
         disableAutoPan : false,
         maxWidth : 0,
         pixelOffset : new google.maps.Size( - 140, 0),
         zIndex : null,
         boxStyle :  { background : "url('tipbox.gif') no-repeat",  width : "280px" },
         closeBoxMargin : "10px 4px 2px 2px", closeBoxURL : "close.gif", 
         infoBoxClearance : new google.maps.Size(1, 1), 
         isHidden : false,
         pane : "floatPane",
         enableEventPropagation : true
     };
      var infoBox;
     function codeproject(address, client) {    
         geocoder.geocode( {
             'address' : address
         },
         function (results, status) {

    if (status == google.maps.GeocoderStatus.OK) {

        map.setCenter(results[0].geometry.location);
      var  marker = new google.maps.Marker( {
            map : map, icon : 'green-dot.png', position : results                      [0].geometry.location, draggable : false, animation : google.maps.Animation.DROP
        });
        //bounce the marker
       // marker.setAnimation(google.maps.Animation.BOUNCE);
        //initialize info box
        infoBox = new InfoBox(myOptions); 
        markerBounds.extend(results[0].geometry.location);
        //listeners
        google.maps.event.addListener(marker, 'mouseover', function () {
        //stop bouncing
       //   marker.setAnimation(null);
         // $("img[src$='iws3.png']").hide();
         //   infowindow.setContent('<b>' + client + '<\/b><br>'+ results[0].formatted_address);
         //  infowindow.open(map, this);
          boxText.innerHTML = "<br>"+client +"<br>"+results[0].formatted_address;

          infoBox.setContent(boxText,marker);
          infoBox.open(map,marker);
            });
             google.maps.event.addListener(marker, 'mouseout', function () {
                 // infowindow.close();
              infoBox.close();
                //start bounce
                //    marker.setAnimation(google.maps.Animation.BOUNCE);
        });

        //ok end
    }
    else {
        if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
            alert("Error Occured during geocode:" + status);
        }
        //  alert('Geocode was not successful for '+client +' the following reason: ' + status);
    }
        });
       }

         function codeAddress(address, client) {
//  var address = document.getElementById('address').value;
geocoder.geocode( {
    'address' : address
},
function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {

        // map.setCenter(results[0].geometry.location);
       infoBox = new InfoBox(myOptions); 

      var  marker = new google.maps.Marker( {
            map : map, 
          // icon : 'smallpin.png',
            position : results[0].geometry.location, draggable : false, animation : google.maps.Animation.DROP
        });
        //make bounds
     //bounce the marker
       // marker.setAnimation(google.maps.Animation.BOUNCE);
        //initialize info box
        markerBounds.extend(results[0].geometry.location);
        //listeners
        google.maps.event.addListener(marker, 'mouseover', function () {
        //stop bouncing
      //  marker.setAnimation(null);
           $("img[src$='iws3.png']").hide();
           // infowindow.setContent('<b>' + client + '<\/b><br>'+ results[0].formatted_address + '<\br>');
            //infowindow.open(map, this);
               boxText.innerHTML = "<br>"+client +"<br>"+results[0].formatted_address ;

          infoBox.setContent(boxText,marker);
          infoBox.open(map,marker);


        });
        google.maps.event.addListener(marker, 'mouseout', function () {
          //  infowindow.close();
         //start bounce
         infoBox.close();
       //   marker.setAnimation(google.maps.Animation.BOUNCE);
        });

        //ok end
    }
    else {
        //  alert('Geocode was not successful for '+client +' the following reason: ' + status);
    }
      });
         }


           //////////////calling the above two functions
      var centerpoint = new google.maps.LatLng(43.652527,  - 79.381961);//for ontario          canada zoom level-7
    //map intializing
     var map = new google.maps.Map(document.getElementById('map'), 
       {
zoom : 4, backgroundColor : '#B5B5B5', draggable : true, center : centerpoint,             mapTypeId : google.maps.MapTypeId.ROADMAP
         });
     ///geocoding multiple addresses
    //bounce markers
    function toggleBounce(mark) {
if (mark.getAnimation() != null) {

    mark.setAnimation(null); 
}
else {
    mark.setAnimation(google.maps.Animation.BOUNCE);
}
    }

    /////
    function putmarker(address,client,lat,lng) {  

    var position = new google.maps.LatLng(lat,lng);
      var  marker = new google.maps.Marker( {
            map : map, icon : 'green-dot.png', position : position, draggable : false,         animation : google.maps.Animation.DROP
        });
        //bounce the marker
       // marker.setAnimation(google.maps.Animation.BOUNCE);
        //initialize info box
        infoBox = new InfoBox(myOptions); 
        markerBounds.extend(position);
        //listeners
        google.maps.event.addListener(marker, 'mouseover', function () {
        //stop bouncing
       //   marker.setAnimation(null);
         // $("img[src$='iws3.png']").hide();
         //   infowindow.setContent('<b>' + client + '<\/b><br>'+ results[0].formatted_address);
         //  infowindow.open(map, this);
          boxText.innerHTML = "<br>"+client +"<br>"+address;

          infoBox.setContent(boxText,marker);
          infoBox.open(map,marker);
        });
        google.maps.event.addListener(marker, 'mouseout', function () {
         //  infowindow.close();
          infoBox.close();
         //start bounce
     //    marker.setAnimation(google.maps.Animation.BOUNCE);
        });

        //ok end
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...