Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru" lang="ru">
- <head>
- <meta name="viewport" content="IE=9, initial-scale=1.0, user-scalable=no; charset=utf-8" />
- <style type="text/css">
- html { height: 100% }
- body { height: 100%; margin: 0px; padding: 0px }
- #map { height: 100% }
- </style>
- <script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
- <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
- <script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js"></script>
- <script type="text/javascript">
- var latlng;
- var markers = [];
- var Polylines = [];
- var myMap;
- var index = 1;
- var directionsDisplay;
- var directionsService = new google.maps.DirectionsService();
- var infoWindow = new google.maps.InfoWindow;
- var mc, mcOptions;
- //var trafficLayer = new google.maps.TrafficLayer();
- //var trafficOn = false;
- var lineSymbol = {
- path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
- };
- var rendererOptions = {
- draggable: true
- };
- var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
- var directionsService = new google.maps.DirectionsService();
- function initialize() {
- directionsDisplay = new google.maps.DirectionsRenderer();
- // latlng = new google.maps.LatLng(47.49430800,34.66911600);
- latlng = new google.maps.LatLng(50.5160683333,30.7816383333);
- var myOptions = {
- zoom: 15,
- center: latlng,
- mapTypeId: google.maps.MapTypeId.ROADMAP,
- disableDoubleClickZoom: true,
- panControl: true,
- zoomControl: true,
- mapTypeControl: true,
- scaleControl: true,
- streetViewControl: true,
- overviewMapControl: true
- };
- myMap = new google.maps.Map(document.getElementById("map"),
- myOptions);
- google.maps.event.addListener(myMap, 'dblclick', function(event) {
- addMarker(event.latLng);
- });
- google.maps.event.addListener(myMap, 'click', function() {
- infoWindow.close();
- });
- mcOptions = {gridSize: 50, maxZoom: 15};
- mc = new MarkerClusterer(myMap, markers, mcOptions);
- //отображение кнопки управления трафиком - все спер с примера, только подцепил свою функцию
- var trafficControlDiv = document.createElement('div');
- trafficControlDiv.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 = 'нажмите для вкл/выкл трафика';
- trafficControlDiv.appendChild(controlUI);
- // Set CSS for the control interior
- var controlText = document.createElement('div');
- controlText.style.fontFamily = 'Arial,sans-serif';
- controlText.style.fontSize = '12px';
- controlText.style.paddingLeft = '4px';
- controlText.style.paddingRight = '4px';
- controlText.innerHTML = '<b>Трафик</b>';
- controlUI.appendChild(controlText);
- google.maps.event.addDomListener(controlUI, 'click', function (){
- if (!trafficOn){
- trafficOn = true;
- trafficLayer.setMap(myMap);
- }else{
- trafficOn = false;
- trafficLayer.setMap(null);
- }
- });
- trafficControlDiv.index = 1;
- myMap.controls[google.maps.ControlPosition.TOP_RIGHT].push(trafficControlDiv);
- directionsDisplay.setMap(myMap);
- directionsDisplay.setPanel(document.getElementById('directionsPanel'));
- google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
- computeTotalDistance(directionsDisplay.getDirections());
- });
- // poly = new google.maps.Polyline(polyOptions);
- // poly.setMap(myMap);
- //NewPolyLine = new google.maps.Polyline(polyOptions);
- //NewPolyLine.setMap(myMap);
- }
- // VisiblePolyLine - Видимость Ломаной на карте из массива ломаных линий (Polyline)
- function VisiblePolyLine ( PolylineIndex, Visible ) {
- if (Visible) {
- Polylines [PolylineIndex].setMap(myMap);
- } else {
- Polylines [PolylineIndex].setMap(null);
- }
- }
- function hexToRgb(hex) {
- // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
- var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
- hex = hex.replace(shorthandRegex, function(m, r, g, b) {
- return r + r + g + g + b + b;
- });
- var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
- return result ? {
- r: parseInt(result[1], 16),
- g: parseInt(result[2], 16),
- b: parseInt(result[3], 16)
- } : null;
- }
- //добавляем маркер и отправляем в массив
- function addMarker(location) {
- marker = new google.maps.Marker({
- position: location,
- map: myMap,
- title: 'Точка'+index
- });
- infoWindow.setContent(marker.title);
- infoWindow.open(myMap, marker);
- google.maps.event.addListener(marker, 'click', function(){
- var mark = this;
- var latLng = mark.getPosition();
- infoWindow.setContent(mark.title);
- infoWindow.open(myMap, mark);});
- markers.push(marker);
- index++;
- document.getElementById('CoordX').value = location.lat();
- document.getElementById('CoordY').value = location.lng();
- //обновляем кластер маркеров
- mc.addMarker(marker);
- }
- function getCoordX(){
- return document.getElementById('CoordX').value;
- }
- function getCoordY(){
- return document.getElementById('CoordY').value;
- }
- function My_LatLng(latitude, longitude){
- var myLatlng = new google.maps.LatLng(latitude, longitude);
- return myLatlng;
- }
- function calcRoute(options) {
- //вытягиваем из массива переданных параметров значения
- //и преобразуем их в формат LatLng
- var option1 = options[0];//начальная точка
- var option2 = options[1];//промежуточные точки
- var option3 = options[2];//конечная точка
- var start = new google.maps.LatLng(option1[0], option1[1]); //первый
- var end = new google.maps.LatLng(option3[0], option3[1]); //последний
- //получаем транзитные точки
- var waypts = [];
- if(option2.length > 0) {
- for(var i = 0, l = option2.length; i < l; i++) {
- temp = option2[i];
- Qcoord = new google.maps.LatLng(temp[0], temp[1])
- waypts.push({
- location:Qcoord,
- stopover:true
- });
- }
- }
- //return;
- var request = {
- origin: start,
- destination: end,
- waypoints: waypts,
- optimizeWaypoints: true,
- travelMode: google.maps.TravelMode.DRIVING
- };
- directionsService.route(request, function(response, status) {
- if (status == google.maps.DirectionsStatus.OK) {
- directionsDisplay.setMap(myMap);
- directionsDisplay.setDirections(response);
- }else{
- alert(status);
- }
- });
- }
- function Reset(){
- directionsDisplay.setMap(null);
- for (var i = 0; i < markers.length; i++) {
- markers[i].setMap(null);
- }
- markers = [];
- index = 1;
- //обновляем кластер маркеров
- mc.clearMarkers();
- //Активных маркеров нет
- document.getElementById('AnimatedMarkerID').value = -1;
- }
- function FindAdres(Adres){
- Reset();
- var geocoder = new google.maps.Geocoder();
- geocoder.geocode( { 'address': Adres}, function(results, status) {
- if (status == google.maps.GeocoderStatus.OK) {
- latlng = results[0].geometry.location;
- myMap.panTo(latlng);
- marker = new google.maps.Marker({
- map: myMap,
- position: latlng,
- animation: google.maps.Animation.BOUNCE,
- title:Adres
- });
- markers.push(marker);
- infoWindow.setContent(marker.title);
- infoWindow.open(myMap, marker);
- //обновляем кластер маркеров
- mc.addMarker(marker);
- } else {
- alert("Ничего не найдено: " + status);
- }
- });
- }
- function ReverseSearchAdres(CoordX, CoordY, Adres){
- Reset();
- latlng = new google.maps.LatLng(CoordX, CoordY);
- myMap.panTo(latlng);
- var marker = new google.maps.Marker({
- map: myMap,
- position: latlng,
- animation: google.maps.Animation.BOUNCE,
- title:Adres
- });
- markers.push(marker);
- infoWindow.setContent(marker.title);
- infoWindow.open(myMap, marker);
- //обновляем кластер маркеров
- mc.addMarker(marker);
- }
- //window.onerror = null;
- //function myOnError(msg, url, lno) {return true}
- // addShopMarker - добавляем маркер торговой точки и отправляем в массив
- function addShopMarker( latitude, longitude, ShopTitle, WeekDay) {
- var myLatlng = new google.maps.LatLng(latitude, longitude);
- var image_00 = {
- url: 'D:/GoogleMaps/images/small_red.png',
- // This marker is 20 pixels wide by 32 pixels tall.
- size: new google.maps.Size(9, 9),
- // The origin for this image is 0,0.
- origin: new google.maps.Point(0,0),
- // The anchor for this image is the base of the flagpole at 0,32.
- anchor: new google.maps.Point(0, 9)
- };
- var image_02 = {
- //url: 'https://chart.googleapis.com/chart?chst=d_bubble_icon_texts_big&chld=home|bb|FFB573|000000|Haunted+House|Hours:+Midnight+to+3:00+AM|Ghouls,+Goblins,+and+Vampires|Bring+your+own+wooden+шашлык'
- //url: 'https://chart.googleapis.com/chart?'
- //+ 'chst=d_map_spin&'
- //+ 'chld=3|45|FFFF42|11|_|First+line|Second+line'
- url: 'https://chart.googleapis.com/chart?'
- + 'chst=d_map_pin_letter_withshadow&'
- + 'chld=ЯЯ|FF0000|0000FF'
- };
- var image_02222 = {
- url: 'D:/GoogleMaps/images/beachflag.png',
- // This marker is 20 pixels wide by 32 pixels tall.
- size: new google.maps.Size(20, 32),
- // The origin for this image is 0,0.
- origin: new google.maps.Point(0,0),
- // The anchor for this image is the base of the flagpole at 0,32.
- anchor: new google.maps.Point(0, 32)
- };
- // Shapes define the clickable region of the icon.
- // The type defines an HTML <area> element 'poly' which
- // traces out a polygon as a series of X,Y points. The final
- // coordinate closes the poly by connecting to the first
- // coordinate.
- var shape = {
- coords: [1, 1, 1, 20, 18, 20, 18 , 1],
- type: 'poly'
- };
- if (WeekDay == 0) {
- marker = new google.maps.Marker({
- position: myLatlng,
- icon: image_00,
- map: myMap,
- title: ShopTitle});
- }
- else
- if (WeekDay == 1) {
- marker = new google.maps.Marker({
- position: myLatlng,
- map: myMap,
- title: ShopTitle});
- }
- else
- if (WeekDay == 2) {
- marker = new google.maps.Marker({
- position: myLatlng,
- icon: image_02,
- shape: shape,
- map: myMap,
- title: ShopTitle});
- }
- //infoWindow.setContent(marker.title);
- //infoWindow.open(myMap, marker);
- markers.push(marker);
- index++;
- google.maps.event.addListener(marker, 'click', function(){
- var mark = this;
- for (var i = 0; i < markers.length; i++) {
- if (markers[i]==marker) { document.getElementById('ClickedMarkerID').value = i; }
- }
- var latLng = mark.getPosition();
- //infoWindow.setContent(mark.title);
- infoWindow.setContent(mark.title.replace('\n', '<p>'));
- infoWindow.open(myMap, mark);});
- document.getElementById('CoordX').value = myLatlng.lat();
- document.getElementById('CoordY').value = myLatlng.lng();
- //обновляем кластер маркеров
- //mc.addMarker(marker);
- }
- // toggleBounce - Анимация маркера по MarkerID
- function toggleBounce(MarkerID) {
- OldAnimatedMarker = document.getElementById('AnimatedMarkerID').value;
- if (OldAnimatedMarker == -1) {
- // Нет анимированого маркера на карте
- markers[MarkerID].setAnimation(google.maps.Animation.BOUNCE);
- //markers[MarkerID].setAnimation(google.maps.Animation.DROP);
- document.getElementById('AnimatedMarkerID').value = MarkerID;
- } else {
- markers[OldAnimatedMarker].setAnimation(null);
- //alert("Остановили Marker " + OldAnimatedMarker);
- if (OldAnimatedMarker == MarkerID) {
- // Убрать аниманицию
- document.getElementById('AnimatedMarkerID').value = -1;
- } else {
- // Убрать аниманицию текущего маркера
- markers[MarkerID].setAnimation(google.maps.Animation.BOUNCE);
- document.getElementById('AnimatedMarkerID').value = MarkerID;
- }
- }
- }
- // Центрирование карты по массиву маркеров
- function MapCentering() {
- // Благодарности:
- // http://xandeadx.ru/blog/javascript/641
- // Область показа маркеров
- var markersBounds = new google.maps.LatLngBounds();
- for (var i = 0; i < markers.length; i++) {
- // Добавляем координаты маркера в область
- markersBounds.extend(markers[i].getPosition());
- }
- // Центрируем и масштабируем карту
- myMap.setCenter(markersBounds.getCenter(), myMap.fitBounds(markersBounds));
- }
- function ShowDirection(MarkersID) {
- var points = [];
- alert("В маршруте " + MarkersID.length + " точек");
- for (var i = 0; i < MarkersID.length; i++) {
- // Добавляем координаты маркера в область
- points.push({
- location:markers[MarkersID[i]].getPosition(),
- stopover:true});
- }
- // Рисуем цикличный маршрут, начало и конец (origin и destination) = Офис склада - markers[0]
- var request = {
- origin: markers[0].getPosition() ,
- // destination: markers[0].getPosition(),
- destination: markers[4].getPosition(),
- waypoints:points,
- travelMode: google.maps.TravelMode.DRIVING
- };
- //alert("request origin " + request.origin );
- directionsService.route(request, function(response, status) {
- if (status == google.maps.DirectionsStatus.OK) {
- //alert("DirectionsStatus OK" );
- directionsDisplay.setDirections(response);
- }
- });
- }
- function computeTotalDistance(result) {
- var total = 0;
- var myroute = result.routes[0];
- for (var i = 0; i < myroute.legs.length; i++) {
- total += myroute.legs[i].distance.value;
- }
- total = total / 1000.0;
- document.getElementById('total').innerHTML = total + ' km';
- }
- //google.maps.event.addDomListener(window, 'load', initialize);
- // AddPolyLine - Добавить Ломаную в масиив ломаных линий (Polyline)
- // HexColor - 16-тиричное значение цвета ломаной линии
- // TrackCoordinates - длинная строка. Содержит массив пар координат точек трека
- //function AddPolyLine ( HexColor, TrackCoordinates) {
- // ShowPolyLine - Динамическое построение ломаной линии (Polyline)
- // TrackCoordinates - длинная строка. Содержит массив пар координат точек трека
- function ShowPolyLine ( HexColor, TrackCoordinates) {
- var polyOptions = {
- icons: [{
- icon: lineSymbol,
- offset: '0',
- repeat: '100px'
- }],
- strokeColor: '#' + HexColor,
- strokeOpacity: 1.0,
- strokeWeight: 1
- }
- // "Чистый" массив _пар_ координат
- LatLangArray = TrackCoordinates.split("}");
- Polylines [Polylines.length] = new google.maps.Polyline(polyOptions);
- NewLine = Polylines [Polylines.length-1];
- NewLine.setMap(myMap);
- path = NewLine.getPath();
- for (var i = 0; i < LatLangArray.length; i++) {
- // _Пара_ координат - массив из 2-х элементов
- LatLangPair = LatLangArray[i].split(";");
- path.push(new google.maps.LatLng(LatLangPair [0], LatLangPair [1]));
- }
- // alert ('__' + NewLine.strokeColor + '___');
- }
- </script>
- </head>
- <body onload="initialize()">
- <div id="map" style="width:100%; height:100%"></div>
- <input type="hidden" id="CoordX" name="CoordX" value="0"></input>
- <input type="hidden" id="CoordY" name="CoordY" value="0"></input>
- <input type="hidden" id="AnimatedMarkerID" name="AnimatedMarker" value="-1"></input>
- <input type="hidden" id="ClickedMarkerID" name="ClickedMarkerID" value="-1"></input>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment