how to add search box to google map with street view - javascript

I want the map to update to the new Address given by the user when enter new Address in the search box. this is what I tried but is not working
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Street View service</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var lag =151.1956316;
var lat = -33.8665433;
function initialize() {
var fenway = new google.maps.LatLng( lat, lag);
var mapOptions = {
center: fenway,
zoom: 14
};
var map = new google.maps.Map(
document.getElementById('map-canvas'), mapOptions);
var panoramaOptions = {
position: fenway,
pov: {
heading: 34,
pitch: 10
}
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'),panoramaOptions);
map.setStreetView(panorama);
}
// search for new Addreess
var addressField = document.getElementById('search_address');
var geocoder = new google.maps.Geocoder();
function search() {
geocoder.geocode(
{'address': addressField.value},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var loc = results[0].geometry.location;
// use loc.lat(), loc.lng()
lat = loc.lat();
lag = loc.lng();
google.maps.event.addDomListener(window, 'load', initialize);
}
else {
alert("Not found: " + status);
}
}
);
};
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="width: 400px; height: 300px"></div>
<div id="pano" style="position:absolute; left:410px; top: 8px; width: 400px; height: 300px;"></div>
<div id="panel">
<input type="text" id="search_address" value=""/>
<button onclick="search();">Search</button>
</div>
</body>
</html>
it tried many option but still not working

There are 2 issues:
the addressField -variable has been defined too early(the input is unknown at this time)
modifying the lag/lat -variables will not have an effect to the map/panorama
(you must assign a LatLng to the center of the map/position of the panorama)

Related

google maps api additional search box

I am struggling to introduce a second search to place a marker like the first search.
I have worked out the coding as below for a general search and marker place and as you can see and have added an extra search box but cannot work out how to make that search box do the same as the first.
Basically I am trying to mark two separate locations simultaneously with one submit button.
Can anyone help or point me in the right direction please
<!-- Google Maps and Places API -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
//declare namespace
var up206b = {};
//declare map
var map;
function trace(message)
{
if (typeof console != 'undefined')
{
console.log(message);
}
}
up206b.initialize = function()
{
var latlng = new google.maps.LatLng(34.070264, -118.4440562);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
var geocoder = new google.maps.Geocoder();`
up206b.geocode = function()
{
var address = $('#address').val();
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,
position: results[0].geometry.location
});
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
up206b.geocode = function()
{
var address = $('#address').val();
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,
position: results[0].geometry.location
});
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
var address = $('#address').val();
</script>
</head>
<body onload="up206b.initialize()">
<div style= "float:left">
</div>
<div style="width:380px; height: 100%; overflow:auto; float:right; padding-left:10px; padding-right:10px;">
<h1>Map Search</h1>
<div style="border:1px solid #ccc; background:#e5e5e5; padding:10px;">
<input type="text" id="address">
<input type="text" id="">
<input type="button" value="Submit" onClick="up206b.geocode()">
</div>
</div>
<div id="map_canvas" style="height:100%; margin-left:400px;"></div>
</body>
</html>
Get value of both inputs, geocode the values that exist and add them to the map.
<!DOCTYPE html>
<html>
<head>
<!-- Google Maps and Places API -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
//declare namespace
var up206b = {};
//declare map
var map;
function trace(message)
{
if (typeof console != 'undefined')
{
console.log(message);
}
}
up206b.initialize = function()
{
var latlng = new google.maps.LatLng(34.070264, -118.4440562);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
var geocoder = new google.maps.Geocoder();
up206b.geocode = function()
{
var addresses = [ $('#address').val(), $('#address2').val()];
addresses.forEach(function(address){
if(address){
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,
position: results[0].geometry.location
});
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
}
</script>
</head>
<body onload="up206b.initialize()">
<div style="position: absolute; top: 0; right: 0; width:380px; height: 500px; overflow:auto; float:right; padding-left:10px; padding-right:10px;">
<h1>Map Search</h1>
<div style="border:1px solid #ccc; background:#e5e5e5; padding:10px;">
<input type="text" id="address">
<input type="text" id="address2">
<input type="button" value="Submit" onClick="up206b.geocode()">
</div>
</div>
<div id="map_canvas" style="height: 500px; width: 500px;"></div>
</body>
</html>

How set the current position center on the map?

I tried different approaches which I found on this site and in web but they don't work for me(
This is my code:
<h:panelGroup id="GMWrapper" style="background-color: red">
<p:gmap widgetVar="mainMap" center="49.835, 24.0083" zoom="15"
id="mainGoogleMap" type="HYBRID"
style="width: 600px; height: 400px" model="#{userPlaces.model}"
styleClass="gmappStyle" onPointClick="handlePointClick(event)" />
<p:commandButton onclick="someFunc()"></p:commandButton>
<script type="text/javascript">
function someFunc() {
if (navigator.geolocation) {
alert("Start")
navigator.geolocation
.getCurrentPosition(success);
alert("Successful!")
var elem = document
.getElementById("mainGoogleMap");
alert("Element was find")
elem.setCenter(new google.maps.LatLng(37.4419, -122.1419));
alert("Good done!");
} else {
error('Geo Location is not supported');
currentLat = 0.0;
currentLng = 0.0;
}
}
var currentLat;
var currentLng;
function success(position) {
currentLat = position.coords.latitude;
currentLng = position.coords.longitude;
}
</script>
</h:panelGroup>
Javascript code works to alert("Element was find")
Also I tried:
elem.setAttribute("center", currentLat.toString() + ", " + currentLng.toString());
elem.setAttribute("center", currentLat + ", " + currentLng);
elem.setAttribute("center", "37.4419, -122.1419");
and few other..
From the google maps docs: panTo(latLng:LatLng|LatLngLiteral) - Changes the center of the map to the given LatLng. If the change is less than both the width and height of the map, the transition will be smoothly animated. Below is a snippet that creates a map and centers the map at a location.
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
map.panTo(new google.maps.LatLng(37.4419, -122.1419));
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

Drag marker on Google maps and receive its updated position [duplicate]

I have made a Google Version 3 Geocoder , I want to be able to pick up the coordinates of the marker when it is dragged or clicked. Below is my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script src="http://maps.google.com/maps/api/js?v=3.5&sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
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);
var marker = new google.maps.Marker({
map: map,
draggable: true,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
<style type="text/css">
#controls {
position: absolute;
bottom: 1em;
left: 100px;
width: 400px;
z-index: 20000;
padding: 0 0.5em 0.5em 0.5em;
}
html, body, #map_canvas {
margin: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body onload="initialize()">
<div id="controls">
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map_canvas"></div>
</body>
</html>
I have tried to use the following code to do this but it does not seem to work.
// Javascript//
google.maps.event.addListener(marker, 'dragend', function(evt){
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});
google.maps.event.addListener(marker, 'dragstart', function(evt){
document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});
map.setCenter(marker.position);
marker.setMap(map);
//HTML//
<div id='map_canvas'></div>
<div id="current">Nothing yet...</div>
That code works just fine if you put it in the correct place:
http://www.geocodezip.com/BlakeLoizides_geocode.html
(inside the callback routine, the marker is local to it)

Google Maps API, driving directions rendering

I am trying to make a call to google maps api to display driving directions based on 2 inputted locations. My skill level is newb.
I am using a notepad to render my html (by pressing ctrl+shift+alt+R), I also tried using xampp to host a local server and then open my html on local (by placing it into htdocs file). While using both of those methods of rendering, each time I input my addresses, the map just blinks and no results are displayed. Is the issue my code or the way I am rendering it? If its the way I am rendering it, could someone please suggest another way I could see/render my html? Thank you very much. Martin
Code:
<!DOCTYPE html>
<html>
<head profile="http://gmpg.org/xfn/11"><style type="text/css">.gm-style .gm-style-mtc
label,.gm-style .gm-style-mtc div{font-weight:400}</style>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% ;position:relative;z-index:1}
#panel {
position: fixed;
bottom: 35px;
background: rgba(99,99,99,0.7);
width: 97.75%;
border:3px solid; #FF3D03
border-radius:3px;
z-index: 15;
font-weight: bold;
font-family: arial;
font-style: normal;
padding: 2px 0px 2px 24px;
}
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?
key=AIzaSyAzbS2nerrvbdvNlsyQO9cDWFNthdoswRU&sensor=false">
</script>
<div id="map_canvas">
<script type="text/javascript">
var address = new google.maps.LatLng(31.208647, 7.861769);
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
<!------------------------------------------------------->
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
center: address,
zoom: 16,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay.setMap(map);
}
<!------------------------------------------------------->
function calcRoute() {
var start = document.forms["frame1"]["address0"].value;
var end = document.forms["frame1"]["address1"].value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
<!------------------------------------------------------->
// var myTitle = document.createElement('h1');
// myTitle.style.color = 'red';
// myTitle.innerHTML = 'menu would go here';
// var myTextDiv = document.createElement('div');
// myTextDiv.appendChild(myTitle);
// map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(myTextDiv);
// var marker = new google.maps.Marker({
// position: new google.maps.LatLng(33.6803003, -116.173894),
// title: "Festival" });
// marker.setMap(map);}
<!------------------------------------------------------->
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</div>
</head>
<!-------------------------------------------------------------------------------->
<body>
<!------------------------------------------------------->
<!-------------------------------------------------------->
<div id="panel" style="color:#ffffff; font-size:18px;" >
<form name="frame1" onsubmit="calcRoute();">
<b>Start: </b>
<input type="text" name="address0">
<b>First Address: </b>
<input type="text" name="address1">
<input type="submit" style="visibility: hidden;">
</form>
</div>
<div id="map-canvas"/>
<!------------------------------------------------------->
<!------------------------------------------------------->
</body>
</html>
Your form submission is reloading the page, destroying the directions response. Change:
<form name="frame1" onsubmit="calcRoute();">
To:
<form name="frame1" onsubmit="calcRoute();return false;">

google maps api geolocation and place search

I want to include Google Maps in my Web App, for that I´m using google maps API.
I am including both place search and geolocation on the map (I have a button for geolocation), but I noticed place search is not working once I pressed the geolocation button, Place Search doesn´t work.
Any ideas?
here is my code
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="theme.css">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<style type="text/css" media="screen">
</style>
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
#target
{
width: 10%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
/*map*/
// Enable the visual refresh
google.maps.visualRefresh = true;
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
/*map end*/
/*search*/
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds);
var input = /** #type {HTMLInputElement} */(document.getElementById('target'));
var searchBox = new google.maps.places.SearchBox(input);
var markers = [];
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
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 = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
/*end search*/
</script>
<script>
/*geolocation*/
var map;
function geolocate() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
/*/geolocation*/
</script>
</head>
<body>
<!--search dialog-->
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$( "#dialog-message" ).dialog({ autoOpen: false });
$(' #dialog-message ').dialog({dialogClass:'search'});
$( "#dialog-message" ).dialog({
modal: true,
});
});
</script>
<style type="text/css" media="screen">
.search { background:rgba(240, 255, 255, 0.4);}
.ui-widget-header {font-family: source sans pro; background: white; border: none; border-radius: 0px}
.pac-container {font-family: source sans pro !important; font-size: 20px !important; min-height: 20% !important}
</style>
<div style="font-family: source sans pro;" id="dialog-message" title="Download complete" class="draggable" >
<p>
<div id="panel" width="100%" height="100%">
<input type="text" id="target" placeholder="Search Box" style="width: 100%; font-family: source sans pro; font-size: 20px; height: auto">
</div>
</div>
<!--/search dialog-->
<table>
<div id="map-canvas"></div>
<table id="commandbar" width="100%" height="5%" cellspacing="0" valign="center" style="background-color:rgba(240, 255, 255, 0.4) ;position:fixed; bottom:0;">
<tr height="2.5%">
<td width="2.5%" height="2.5%" >
<img src="browser_resources/close.png" class="button" onclick="window.close()" width="10em">
</td>
<td width="2.5%" height="2.5%" >
<img src="browser_resources/new_window.png" class="button" onclick="window.open('maps.html','_blank', 'location=no, menubar=no, status=no, titlebar=no' )" width="100%">
</td>
<td width="1px"></td>
<td width="1px" id="divider" bgcolor="#999999">
</td>
<td width="1px"></td>
<td width="2.5%">
<img src="maps_resources/Search.png" class="button" onclick="$( '#dialog-message' ).dialog( 'open' ); " width="100%">
</td>
<td width="2.5%">
<img src="maps_resources/Search.png" class="button" onclick="geolocate()" width="100%">
</td>
<td width="95%"></td>
</tr>
</table>
</body>
</html>
You are overwriting the visible map inside geolocate with a new Maps-instance. But the Maps-instance used for the places-related code is still the instance created in initialize(which still exists as an object, but is no longer bound to map you see). Therefore your places-code still works, but you don't see any changes.
Solution: instead of creating a new Maps-instance inside geolocate make the Maps-instance created inside initialize global accessible(by removing the var-keyword)
remove the var-keyword inside initialize():
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
Note: you've defined the function initialize() 2 times, only the 2nd function is important here, the first function will be overwritten.
Remove this from geolocate() map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
Also remove this from the document:<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"><script>It's not the issue here, but there may occur problems when you include the API-script multiple times

Categories