Google Map : Setting marker through several input fields - google-maps-api-3

how do I change the location of a marker based on address input? I know there's google places autocomplete to do the job, but the requirement is to update the map marker after filling in the address form.
JS Fiddle can be found here:
http://jsfiddle.net/fhft7bfg/2/
HTML:
<input id="route" placeholder="Street"></input>
<input id="locality" placeholder="City"></input>
<input id="administrative_area_level_1" placeholder="State"></input>
<input id="postal_code" placeholder="Postal Code"></input>
<input id="country" placeholder="Country"></input>
<div id="map-canvas"></div>
JS:
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// To add the marker to the map, use the 'map' property
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
}
google.maps.event.addDomListener(window, 'load', initialize);

make the map and the marker global
modify the codeAddress function from Google's simple geocoder example to use your form elements and to move the marker if it already exists.
working fiddle
working code snippet:
// modified from https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
var geocoder = new google.maps.Geocoder();
function codeAddress() {
var street = document.getElementById("route").value;
var city = document.getElementById("locality").value;
var state = document.getElementById("administrative_area_level_1").value;
var postcode = document.getElementById("postal_code").value;
var country = document.getElementById("country").value;
var address = street +"," + city + "," + state +"," + postcode + "," + country;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (marker && marker.setPosition) {
marker.setPosition(results[0].geometry.location);
} else {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
// global variables
var marker;
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// To add the marker to the map, use the 'map' property
marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
}
google.maps.event.addDomListener(window, 'load', initialize);
input{display:block}
#map-canvas{background:#ccc; width:500px; height:300px}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="route" placeholder="Street" value="Beacon St"></input>
<input id="locality" placeholder="City" value="Boston"></input>
<input id="administrative_area_level_1" placeholder="State" value="MA"></input>
<input id="postal_code" placeholder="Postal Code" value="02215"></input>
<input id="country" placeholder="Country" value="US"></input>
<input id="geocode" type="button" onclick="codeAddress();" value="geocode"/>
<div id="map-canvas"></div>

Related

Trouble getting google map to update location through geocoding a users search

I am trying to have my map update with the users input in the mapSearch box when they hit submit but I'm missing something that's not connecting the submit onclick function with the latlng variable.
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng =new google.maps.LatLng(-34.397,150.644);
var mapProp = {
center: latlng,
}
var map=new google.maps.Map(document.getElementById("googleMap"), mapProp);
};
var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
google.maps.event.addDomListener(searchBox, 'places_changed', function(){
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i=0; place=places[i]; i++){
bounds.extend(place.geometry.location);
}
});
$( "#Submit" ).click(function codeAddress(){
var address = document.getElementById("mapsearch").value;
geocoder.geocode( {'mapsearch': 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);
}
});
});
I get a javascript error with the posted code: InvalidValueError: unknown property mapsearch on this line: geocoder.geocode( {'mapsearch': address}, (that should be 'address'):
$("#Submit").click(function codeAddress() {
var address = document.getElementById("mapsearch").value;
geocoder.geocode({
'address': address
},
code snippet:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapProp = {
center: latlng,
zoom: 3
}
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
$("#Submit").click(function codeAddress() {
var address = document.getElementById("mapsearch").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,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#googleMap {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="Submit" type="button" value="submit" />
<input id="mapsearch" value="New York, NY" />
<div id="googleMap"></div>

Implementing google place autocomplete

This is my code for places autocomplete and search.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">
</script>
<script>
var geocoder;
var map;
function initialize() {
var input = document.getElementById('address');
var options = {
componentRestrictions: {country: "in"}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(18.52043030000, 73.85674369999);
var mapOptions = {
zoom: 15,
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
}
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,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
This is my html code.
<input id="address" type="textbox" size="30">
<input type="button" value="Search" onclick="codeAddress()">
It is working fine but I dont want to user to click the button. When suggestions appeared, and when user select any of suggestion options, map will have to navigate to that place. How do I do this???
When User select any option from dropdown, map should navigate to that place.
Take a look at this example and the implementation of the place_changed event.
var place = autocomplete.getPlace();
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
}
This way you can pan the map to the location of the autocomplete result.
This is my working code..
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">
</script>
<script>
var geocoder;
var map;
function initialize() {
var input = document.getElementById('address');
var options = {
componentRestrictions: {country: "in"}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(18.52043030000, 73.85674369999);
var mapOptions = {
zoom: 15,
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.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(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
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,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Now user can select option from dropdown and map will navigate to that place. And also on search button click.
Hope this might help you
function initialize(){
var mapOptions = {//Map Properties
zoom:12,
center: Bangalore
};
googleMap = new google.maps.Map(document.getElementById('map-holder'),mapOptions);//map-holder is a div which holds map in my html
var defaultBounds = new google.maps.LatLngBounds(//bounds for Bengaluru
new google.maps.LatLng(12.7342888,77.3791981),
new google.maps.LatLng(13.173706,77.8826809)
);
googleMap.fitBounds(defaultBounds);
var input = (document.getElementById('searchInput'));//search input element
googleMap.controls[google.maps.ControlPosition.TOP_LEFT].push(input);//binding it to map
var searchBox = new google.maps.places.SearchBox((input));
google.maps.event.addListener(searchBox, 'places_changed', function() {//triggers when search is performed
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
bounds.extend(place.geometry.location);
//googleMap.fitBounds(place.geometry.viewport);
}
googleMap.fitBounds(bounds);
});
google.maps.event.addListener(googleMap, 'bounds_changed', function() {
var bounds = googleMap.getBounds();
searchBox.setBounds(bounds);
})
}

Place Markers from Name, Address and Post Code

In my domain model, for the entities in question, I have the:
Name of the place (e.g. Waterstones Wakefield)
The Street Addresses (e.g. 61-62 Bishopgate Walk)
And the Post Code (e.g. WF1 1YB)
From the above three pieces of information, how can I get a Marker placed on the Map? I am using Google Maps API 3.
Thanks
Try this example:
HERE THE ORIGINAL
HTML
<body onload="initialize()">
<div>
<input id="address" type="text" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas" style="height:90%;top:30px"></div>
</body>
JS
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
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,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>

How to enter street address directly in the code

I want to use the google map api v3 like in this example https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-simple
but without this input field
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
I want to specify the street address for example "75 wall st, new york" directly in the code. How do I do this? Below is the code from that sample url. Anyone know what needs to be removed/added to this?
<link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
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,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas" style="height:90%;top:30px"></div>
I would imagine you could update the function to do this:
function codeAddress(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);
}
});
}
And once you want to update the map, just call:
codeAddress('75 wall st, new york');
If you're using jQuery you could put this in your document ready function, or in another part of your code.

Google Maps Api v3: Info window displaying same information for all the markers on the map

I'm working on this code for a certificate program, I tried to get some help from the instructors but they don't seem familiar with Google Map Apis and the requirement is to display multiple markers from addresses stores in an XML file once a search is performed, i.e I look for John, I get his markers in addition to markers for all of the people whose address is stored and specified in my XML file. So the goal is to be able to display say 5 markers for 5 people and their respective info windows.
I'm able to get all markers to display once a search is performed, I can also get the info windows but the info displayed in all info windows is the same in all markers, it displays the information for the name searched for. You could if you want test with the name Larry, zoom out to other markers and see that they all display the same name. I have no idea why? When I looked at fixes, I found nothing for google API v3 only stuff link a bindEvent for the Api v2. Any help would be highly appreciated, I don't know how to stop the for loop from making all the info windows the same. Thanks.
The code is bellow:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var geocoder;
var map;
var marker;
function load() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("mymap"), myOptions);
}
function showAddress(theAddress) {
var myaddress = theAddress
if (geocoder) {
geocoder.geocode( { 'address': myaddress}, 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);
}
});
}
}
function showAllAddress(AllAddress) {
var myaddress = AllAddress
if (geocoder) {
geocoder.geocode( { 'address': myaddress}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
// Create Info Window
var infowindow = new google.maps.InfoWindow({
content: document.getElementById("theName").innerHTML = fiobj[0].firstChild.data + " " + lastobj[0].firstChild.data+"<br />" + addressobj[0].firstChild.data+"<br />" + phoneobj[0].firstChild.data+"<br />" + emailobj[0].firstChild.data+"<br />"
});
// click event for marker
google.maps.event.addListener(marker, 'click', function() {
// Opening the InfoWindow
infowindow.open(map, marker);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
function createRequestObject() {
var ro
var browser = navigator.appName
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP")
}else{
ro = new XMLHttpRequest()
}
return ro
}
var http = createRequestObject()
function sndReq() {
http.open('get', 'http://idrir.userworld.com/ajax/gmap.xml', true)
http.onreadystatechange = handleResponse
http.send(null)
}
function handleResponse() {
if(http.readyState == 4){
document.getElementById("theName").innerHTML = ""
document.getElementById("address").innerHTML = ""
document.getElementById("phone").innerHTML = ""
document.getElementById("email").innerHTML = ""
var response = http.responseXML.documentElement
listings=response.getElementsByTagName("LISTING")
for (i=0;i<listings.length;i++) {
firstobj = listings[i].getElementsByTagName("FIRST")
if (firstobj[0].firstChild.data == document.getElementById("first").value){
fiobj = listings[i].getElementsByTagName("FIRST")
lastobj = listings[i].getElementsByTagName("LAST")
addressobj = listings[i].getElementsByTagName("ADDRESS")
phoneobj = listings[i].getElementsByTagName("PHONE")
emailobj = listings[i].getElementsByTagName("EMAIL")
//do not use this code bellow
// document.getElementById("theName").innerHTML = firstobj[0].firstChild.data + " " + lastobj[0].firstChild.data
// document.getElementById("address").innerHTML = addressobj[0].firstChild.data
// document.getElementById("phone").innerHTML = phoneobj[0].firstChild.data
// document.getElementById("email").innerHTML = emailobj[0].firstChild.data
theAddress = addressobj[0].firstChild.data
showAddress(theAddress)
}
}
//added for loop to add markers
for (i=0;i<listings.length;i++) {
fobj = listings[i].getElementsByTagName("FIRST")
lobj = listings[i].getElementsByTagName("LAST")
aobj = listings[i].getElementsByTagName("ADDRESS")
pobj = listings[i].getElementsByTagName("PHONE")
eobj = listings[i].getElementsByTagName("EMAIL")
AllAddress = aobj[0].firstChild.data
showAllAddress(AllAddress)
}
}
}
</script>
</head>
<body onload="load()">
<form id="search">
<input type="text" id="first" />
<input type="button" value="Search Phonebook" onClick="sndReq()" />
</form>
<div id="theName"></div>
<div id="address"></div>
<div id="phone"></div>
<div id="email"></div>
<div id="mymap" style="width: 500px; height: 300px"></div>
</body>
</html>
I use this and it works... but I'm not a pro: my issue right now
var image = 'http://localhost:3000/images/icons/map/icons/icehockey.png';
var myLatlng_1 = new google.maps.LatLng(53.9515,-113.116);
var contentString_1 = "<b>Provident Place (formerly Redwater Multiplex) Ice Rink</b><br> Redwater, Alberta, Canada<br><b><a href='http://localhost:3000/rink/redwater/provident-place-formerly-redwater-multiplex'>Go To The Rink's Profile</a></b>";
var infowindow_1 = new google.maps.InfoWindow({content: contentString_1});
var marker_1 = new google.maps.Marker({
position: myLatlng_1,
map: map,
icon: image
});
google.maps.event.addListener(marker_1, 'click', function() {
infowindow_1.open(map,marker_1);
});
var myLatlng_2 = new google.maps.LatLng(53.4684,-113.409);
var contentString_2 = "<b>Ridgewood Skating Rink Ice Rink</b><br> Edmonton, Alberta, Canada<br><b><a href='http://localhost:3000/rink/edmonton/ridgewood-skating-rink'>Go To The Rink's Profile</a></b>";
var infowindow_2 = new google.maps.InfoWindow({content: contentString_2});
var marker_2 = new google.maps.Marker({
position: myLatlng_2,
map: map,
icon: image
});

Resources