﻿<!DOCTYPE html>
<html>
  <head>
	<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
      .controls {
        margin-top: 10px;
        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);
      }

      #pac-input {
        background-color: #fff;
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
        margin-left: 12px;
        padding: 0 11px 0 13px;
        text-overflow: ellipsis;
        width: 300px;
      }

      #pac-input:focus {
        border-color: #4d90fe;
      }

      .pac-container {
        font-family: Roboto;
      }

      #type-selector {
        color: #fff;
        background-color: #4d90fe;
        padding: 5px 11px 0px 11px;
      }

      #type-selector label {
        font-family: Roboto;
        font-size: 13px;
        font-weight: 300;
      }
      #target {
        width: 345px;
      }
    </style>
	
	<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyArODwYAGa5DnNo98WNnN4zZKnFU6iLNnc&language=pt&region=pt&libraries=places&callback=initialize"
         async defer>
	</script>

<script>
	var map;
	var geocoder;
	var markers = [];
	var infowindow;
	var infowindow;
	var MarkImage = "http://www.mrkt.abmn.pt/custmarker.png";
	var position //[40.5425, -7.8818];

	//%PlaceHolder_Markimg%

    function initialize() {
		infowindow = new google.maps.InfoWindow({size: new google.maps.Size(80, 50)});

		var coordinatesCenter = getCordinateDefault();
				
		
		geocoder = new google.maps.Geocoder();
		map = new google.maps.Map(document.getElementById("map"), {          		
			zoom: 7,
			center: coordinatesCenter,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			disableDefaultUI: true,
	        zoomControl: true,
            mapTypeControl: true,
			streetViewControl: true,
        });		
				
		<!-- Evento para fechar a janela de info sempre que há um click no mapa -->
		google.maps.event.addListener(map, "click", function() {
			infowindow.close();
		});	
		//markerAddDefault();
		
		initAutocomplete(map);
	}
	
	function initAutocomplete(map) {
        // Create the search box and link it to the UI element.
        var input = document.getElementById("pac-input");
        var searchBox = new google.maps.places.SearchBox(input);
		
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        // Bias the SearchBox results towards current maps viewport.
        map.addListener("bounds_changed", function() {
          searchBox.setBounds(map.getBounds());
        });

        var markers = [];
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener("places_changed", function() {
          var places = searchBox.getPlaces();

          if (places.length == 0) {
            return;
          }

          // Clear out the old markers.
		  markerDeleteAll();
		  		  
          // For each place, get the icon, name and location.
          var bounds = new google.maps.LatLngBounds();
		  if (places.length > 0) {
			var place = places[0]
			var icon = {
			  url: place.icon,
			  size: new google.maps.Size(71, 71),
			  origin: new google.maps.Point(0, 0),
			  anchor: new google.maps.Point(17, 34),
			  scaledSize: new google.maps.Size(25, 25)
			};
			
			var marker = markerAdd(place.geometry.location.lat(), place.geometry.location.lng());
			geocodePosition(marker, true);

			if (place.geometry.viewport) {
			  // Only geocodes have viewport.
			  bounds.union(place.geometry.viewport);
			} else {
			  bounds.extend(place.geometry.location);
			}
			
			map.fitBounds(bounds);
		  }	 
        });
      }
	
	function geocodePosition(marker, drop) {
		if (geocoder == null) { 
			geocoder = new google.maps.Geocoder();
		}
	
		geocoder.geocode({		
			latLng: marker.getPosition() }
			, function(responses) {
				if (responses && responses.length > 0) {
					marker.formatted_address = responses[0].formatted_address;
				} else {
					marker.formatted_address = "Cannot determine address at this location.";
				}
				
				infowindow.setContent(marker.formatted_address + "<br>coordinates: " + marker.getPosition().toUrlValue(6));
				infowindow.open(map, marker);

				if (drop) {
					var args = JSON.stringify(responses[0]);	
					CodeResponse(args);					
				}
			}
		);
	}
	
	function CodeResponse(args) {	
		return window.chrome.webview.hostObjects.callbackObj.codeResponse(args);
	}

	function codeAddress() {	
		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);
			
				if (marker) {
					marker.setMap(null);
					if (infowindow) infowindow.close();
				}
			
				marker = new google.maps.Marker({
					map: map,
					draggable: true,
					position: results[0].geometry.location
				});
	  
				google.maps.event.addListener(marker, "dragend", function() {
					CodeResponse();
				});
	  
				google.maps.event.addListener(marker, "click", function() {
					if (marker.formatted_address) {
						infowindow.setContent(marker.formatted_address + "<br>coordinates: " + marker.getPosition().toUrlValue(6));
					} else {
						infowindow.setContent(address + "<br>coordinates: " + marker.getPosition().toUrlValue(6));
					}
					
					infowindow.open(map, marker);
				});
				
				google.maps.event.trigger(marker, "click");
			} else {
				alert("Geocode was not successful for the following reason: " + status);
			}
		});
	}		
	
	function getCordinateDefault () {
		var coordinatesCenter;
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function (position) { 
				coordinatesCenter = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			});
		}
		
		if (coordinatesCenter == null) {			
			coordinatesCenter = new google.maps.LatLng(39.757086, -7.552296);
		}
		return coordinatesCenter;
	}
		
	function markerDeleteAll () {
		setMapOnAll(null);
		infowindow.close();	
		markers = [];				
	}
		
	function markerAddDefault()
	{
		var coordinatesCenter = getCordinateDefault();
		markerAdd(coordinatesCenter.lat(), coordinatesCenter.lng());
	}
	
	function markerAdd(lat, lng) {	
		var ponto = new google.maps.LatLng(lat, lng);		
		var marker = new google.maps.Marker({
			map: map,
			icon: MarkImage,
			draggable: true
		});
		marker.setPosition(ponto);		

		google.maps.event.addListener(marker, "dragstart", function() {
			infowindow.close();
		});
		
		google.maps.event.addListener(marker, "dragend", function() {
			geocodePosition(marker, true);
		});
		
		geocodePosition(marker)
				
		map.setCenter(ponto);
		
		//Adicionar à lista
		markers.push(marker);
		return marker; 
	}
	
	// Sets the map on all markers in the array.
	function setMapOnAll(map) {
		for (var i = 0; i < markers.length; i++) {
			markers[i].setMap(map);
		}
	}			
	</script>    
	
  </head>
  <body>
	<input id="pac-input" class="controls" type="text" placeholder="Pesquisa...">
	<div id="map"</div>
	<div style="display:none;">
        <input type="hiden" id="txtEndereco" name="txtEndereco" />
        <input type="text" id="txtLatitude" name="txtLatitude" />
        <input type="text" id="txtLongitude" name="txtLongitude" />		
		<input type="button" value="Geocode" onclick="codeAddress()">
	</div>
	<div style="display:none;">
        <input type="hiden" id="txtEndereco" name="txtEndereco" />
        <input type="text" id="txtLatitude" name="txtLatitude" />
        <input type="text" id="txtLongitude" name="txtLongitude" />		
		<input type="button" value="Geocode" onclick="codeAddress()">
	</div>
  </body>
