Объединение Google Maps (основной выпуск Javascript) - PullRequest
0 голосов
/ 17 декабря 2018

Надеюсь, что кто-то может указать на что-то действительно очевидное (я действительно не знаю Javascript).В основном у меня есть две карты, одна из которых выполняет геокодирование на основе адреса, переданного через PHP, а другая - перетаскивает список местоположений из БД MySQL в файл XML.

Обе карты отлично работают изолированно.Однако мне нужно объединить их, поэтому на одной карте отмечены местоположения в файле XML, а также показан маркер геокодирования.Код этих двух комбинаций приведен ниже:

<script>
  var customLabel = {
    restaurant: {
      label: 'R'
    },
    bar: {
      label: 'B'
    }
  };

  var geocoder;
var address ="<?php
foreach ($records as $record)
{
    print htmlspecialchars($record['Address']);
}
?>";

 /// Start of XML Lookup Map

    function initialize() {
    var map = new google.maps.Map(document.getElementById('map_canvas'), {
      center: new google.maps.LatLng(-33.863276, 151.207977),
      zoom: 6
    });


    var infoWindow = new google.maps.InfoWindow;

      // Change this depending on the name of your PHP or XML file
      downloadUrl('test.php', function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName('marker');
        Array.prototype.forEach.call(markers, function(markerElem) {
          var id = markerElem.getAttribute('id');
          var name = markerElem.getAttribute('name');
          var address = markerElem.getAttribute('address');
          var type = markerElem.getAttribute('type');
          var point = new google.maps.LatLng(
              parseFloat(markerElem.getAttribute('lat')),
              parseFloat(markerElem.getAttribute('lng')));

          var infowincontent = document.createElement('div');
          var strong = document.createElement('strong');
          strong.textContent = name
          infowincontent.appendChild(strong);
          infowincontent.appendChild(document.createElement('br'));

          var text = document.createElement('text');
          text.textContent = address
          infowincontent.appendChild(text);
          var icon = customLabel[type] || {};



          var marker = new google.maps.Marker({
            map: map,
            position: point,
            label: icon.label
          });


          var circle = new google.maps.Circle({
            map: map,
            radius: 200000,    // 10 miles in metres
            fillColor: '#AA0000'
            });
            circle.bindTo('center', marker, 'position');





        });
      });
    }

  function downloadUrl(url, callback) {
    var request = window.ActiveXObject ?
        new ActiveXObject('Microsoft.XMLHTTP') :
        new XMLHttpRequest;

    request.onreadystatechange = function() {
      if (request.readyState == 4) {
        request.onreadystatechange = doNothing;
        callback(request, request.status);
      }
    };

    request.open('GET', url, true);
    request.send(null);
  }

  function doNothing() {}

  /// End of XML Lookup Map

  /// Start of Geocoding Map

  function initialize() {
 geocoder = new google.maps.Geocoder();
 var latlng = new google.maps.LatLng(-34.397, 150.644);
 var myOptions = {
  zoom: 7,
  center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: 
google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (geocoder) {
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
      map.setCenter(results[0].geometry.location);

        var infowindow = new google.maps.InfoWindow(
            { content: '<b>'+address+'</b>',
              size: new google.maps.Size(150,50)
            });

        var markerz = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map, 
            title:address
        }); 



    // Add circle overlay and bind to marker
    var circle = new google.maps.Circle({
      map: map,
      radius: 200000,    // 10 miles in metres
      fillColor: '#AA0000'
    });
    circle.bindTo('center', markerz, 'position');


        google.maps.event.addListener(marker, markerz, 'click', function() {
            infowindow.open(map,marker);
        });

      } else {
        alert("No results found");
      }
    } else {
      alert("Geocode was not successful for the following reason: " + 
status);
    }
  });
 }
}

  /// End of Geocoding Map

</script>

Любое руководство приветствуется!

1 Ответ

0 голосов
/ 17 декабря 2018

Спасибо @Джон Смит, решил эту проблему.Выкладываю рабочий код ниже.Это позволит искать и выводить геокодированный адрес, а также извлекать и закреплять координаты широты / долготы из XML-файла через PHP на одной карте.

 <script>
  var customLabel = {
    restaurant: {
      label: 'R'
    },
    bar: {
      label: 'B'
    },
    stockingcenter: {
      label: 'S'
    }
  };

  var geocoder;
var address ="<?php
foreach ($records as $record)
{
print htmlspecialchars($record['Address__c']);
}
?>";

 /// Start of XML Lookup Map

    function initialize() {
    var map = new google.maps.Map(document.getElementById('map_canvas'), {
      center: new google.maps.LatLng(51.5477187, -0.3150843),
      zoom: 6
    });


    var infoWindow = new google.maps.InfoWindow;

      // Change this depending on the name of your PHP or XML file
      downloadUrl('test.php', function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName('marker');
        Array.prototype.forEach.call(markers, function(markerElem) {
          var id = markerElem.getAttribute('id');
          var name = markerElem.getAttribute('name');
          var address = markerElem.getAttribute('address');
          var type = markerElem.getAttribute('type');
          var point = new google.maps.LatLng(
              parseFloat(markerElem.getAttribute('lat')),
              parseFloat(markerElem.getAttribute('lng')));

          var infowincontent = document.createElement('div');
          var strong = document.createElement('strong');
          strong.textContent = name
          infowincontent.appendChild(strong);
          infowincontent.appendChild(document.createElement('br'));

          var text = document.createElement('text');
          text.textContent = address
          infowincontent.appendChild(text);
          var icon = customLabel[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            label: icon.label
          });
           marker.addListener('click', function() {
            infoWindow.setContent(infowincontent);
            infoWindow.open(map, marker);
          }); 


        });
      });




  function downloadUrl(url, callback) {
    var request = window.ActiveXObject ?
        new ActiveXObject('Microsoft.XMLHTTP') :
        new XMLHttpRequest;

    request.onreadystatechange = function() {
      if (request.readyState == 4) {
        request.onreadystatechange = doNothing;
        callback(request, request.status);
      }
    };

    request.open('GET', url, true);
    request.send(null);
  }

  function doNothing() {}

  /// End of XML Lookup Map


   /// Start of Geocoding Map


       geocoder = new google.maps.Geocoder();
        var myOptions = {
                         zoom: 6};

  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
     if (geocoder) {
        geocoder.geocode( { 'address': address}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
             if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
               map.setCenter(results[0].geometry.location);

            var infowindow = new google.maps.InfoWindow(
              { content: '<b>'+address+'</b>',
                size: new google.maps.Size(150,50)
              });

    var markerz = new google.maps.Marker({
        position: results[0].geometry.location,
        map: map, 
        title:address
    }); 



// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
  map: map,
  radius: 200000,    // 10 miles in metres
  fillColor: '#4e63a1'
});
circle.bindTo('center', markerz, 'position');


    google.maps.event.addListener(markerz, 'click', function() {
        infowindow.open(map,markerz);
    });

  } else {
    alert("No results found");
  }
} else {
  alert("Geocode was not successful for the following reason: " + 
status);
}
});
}
}

/// End of Geocoding Map
</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...