Google Maps Api v3: Info window displaying same information for all the markers on the map - google-maps-api-3

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
});

Related

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);
})
}

Open Google Map in new window on click

I have embedded a Google map in my web page. Now I want to open that same map in a new pop-up window. Can any one let me know how to do it?
I tried few option which I got through google search and from SF but they are not working. In one of the forum it was mentioned that wrap the div which has the map with tag but what URL has to be passed to it?
#Update
Here is the code:
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script>
var amsterdam=new google.maps.LatLng(18.5204303,73.85624369999992);
var lat;
var long;
function initialize()
{
var mapProp = {
center:amsterdam,
zoom:8,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var geocoder = new google.maps.Geocoder();
var reslatlon = null;
var location = "pune,maharashtra";
if(!geocoder) {
geocoder = new google.maps.Geocoder();
}
var geocoderRequest = {
address: location
}
var myCity = null;
geocoder.geocode(geocoderRequest, function(results, status) {
//alert(status);
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
reslatlon = results[0].geometry.location;
lat = results[0].geometry.location.hb;
long = results[0].geometry.location.ib;
amsterdam = new google.maps.LatLng(results[0].geometry.location.hb,results[0].geometry.location.ib);
//alert(results[0].geometry.location.hb + " , " + results[0].geometry.location.ib);
myCity = new google.maps.Circle({
center:amsterdam,
radius:25000,
strokeColor:"#0000ff",
strokeOpacity:0.8,
strokeWeight:2,
fillColor:"#0000ff",
fillOpacity:0.4,
map:map
});
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function openWin(){
alert(lat + " , " + long);
window.open("http://maps.google.com/maps? ll="+lat+","+long,'MYMAP','height=400,width=600');return true;
}
</script>
</head>
<body>
<a target="MYMAP" onclick="openWin()" href="">
<div id="googleMap" style="width:500px;height:380px;"></div></a>
</body>
</html>

Google Maps API - External link to map markers and open infowindow

I have a map populating with markers taken from an xml file that are stored in a database. Below the map I am pulling the same info from each marker and displaying them as listings. What I'm trying to to is create a <a href=""> type link that will open the corresponding marker and infowindow beside each listing. Here is my page, it might better explain what I mean: http://poultry.ie/plugin/page/breeders
Here is my code:
<script type="text/javascript">
//<![CDATA[
var redpin = new google.maps.MarkerImage('http://labs.google.com/ridefinder/images/mm_20_red.png',
new google.maps.Size(20,32),
new google.maps.Point(0,0),
new google.maps.Point(0,32)
);
var redpinshadow = new google.maps.MarkerImage('http://labs.google.com/ridefinder/images/mm_20_shadow.png',
new google.maps.Size(37,32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32)
);
function load() {
var gmarkers = [];
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.5076512854544, -7.701416015625),
zoom: 7,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("http://poultry.ie/plugins/CustomPages/pages/phpsqlajax_genxml3.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var phone = markers[i].getAttribute("phone");
var breeds = markers[i].getAttribute("breeds");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b><br />" + address + "<br/>" + phone + "<br/>" + breeds;
var marker = new google.maps.Marker({
map: map,
shadow: redpinshadow,
icon: redpin,
position: point
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
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() {}
//]]>
</script>
And the php that is dynamically displaying the listings (for this one county):
//Armagh
$data = mysql_query("SELECT * FROM markers WHERE address='Armagh'")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print '<div class="county all armagh">';
Print "<h4>".$info['name'] . "</h4> ";
Print "<em>".$info['address'] . "</em><br /> ";
Print "".$info['phone'] . "<br /> ";
Print 'See on Map<br />';
Print "<em>Breeds:</em> ".$info['breeds'] . "<hr/></div>";
}
The <a href="javascript:myclick( is from a previous attempt at creating this, it doesn't actually have a function at the moment.
I have tried to apply many examples to my code without success as my knowledge of javascript is fairly limited to say the least. My above code might also not be the cleanest as it is my putting together from a lot of examples.
Here is an example (ported from Mike Williams' v2 tutorial) which loads markers from an xml file and has a clickable sidebar

Google Maps API v3 - set bounds and center not working with Ajax/PHP

I am trying to get the automatic bounds-and-zoom functions in Google Maps API 3 to work with Ajax/PHP-generated markers and having no luck so far. The PHP-gen map works fine (with manual center and zoom) until I add the bounds-related code, which I got from here at stackoverflow. It now just centers at (0,0) in the middle of the ocean and only the first of my markers displays. The former doesn't seem totally surprising based on the initial center declaration of (0,0), but it worked for the original poster and I'm a Javascript noob so don't really know what I'm doing! I would be eternally grateful if someone could spot the problem.
Here's my current code (I've left out the icon definitions to save space):
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 10,
mapTypeId: '<?php echo $maptype; ?>'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("gen-xml.php?<?php if($country) echo "country=$country"; if($location) echo "&location=$location"; ?>", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("city");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lon")));
var html = "<div class='infowindow'>" + name + " <br/>" + address + " <br/></div>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bounds.extend(myLatLng);
map.fitBounds(bounds);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
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() {}
Try
bounds.extend(point);
instead of
bounds.extend(myLatLng);
which seems not to be related to any part of your code

How to get the longitude and lattitude from an address without showing map

I want to get latitude and longitude from address in one of my asp.net application, i know it s possible using google apis but i want to do it without showing google map. How can i do that?
I also want to get distance between two pairs of latitude and longitude. Please guide me in that regards also.
Thanks
Pankaj
You need to do everything in an onload function, as described at http://code.google.com/apis/maps/documentation/introduction.html#Loading_the_Maps_API . The basic idea (using version 2 of the API) is :
var coder = new GClientGeocoder();
coder.getLatLng(
"Addr to Geocode",
function(point) {
if (point) {
// Do something with GLatLng point
}
}
);
To get the distance (in meters), do:
point1.distanceFrom(point2)
Or try this..
Note: You will want to replace the “YabbaDabbaDoo” with your own Google Maps API Key.
In the body of your web page, lets place some textboxes on the form so that we can enter the address details that we want to find the co-ordinates for (and a button to perform the co-ordinates calculation):
Address Line 1:
Address Line 2:
Town:
Postcode:
Country:
Latitude:
Longitude:
Now all that is left to do is to create the javascript function that will perform the calculation. So here it is:
function calculateCoordinates() {
var txtAddress1 = document.getElementById('<%= txtAddress1.ClientID%>');
var txtAddress2 = document.getElementById('<%= txtAddress2.ClientID%>');
var txtTown = document.getElementById('<%= txtTown.ClientID%>');
var txtPostcode = document.getElementById('<%= txtPostcode.ClientID%>');
var txtCountry = document.getElementById('<%= txtCountry.ClientID%>');
var txtLatitude = document.getElementById('<%= txtLatitude.ClientID%>');
var txtLongitude = document.getElementById('<%= txtLongitude.ClientID%>');
var address = txtAddress1.value + ', ';
address += txtAddress2.value + ', ';
address += txtTown.value + ', ';
address += txtPostcode.value + ', ';
address += txtCountry.value;
var geocoder;
geocoder = new GClientGeocoder();
geocoder.getLatLng(address, function(latlng) {
if (!latlng) {
alert(address + ' not found');
} else {
txtLatitude.value = latlng.lat();
txtLongitude.value = latlng.lng();
}
});
}
try this code...........
In PAge load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetPhysiciansForMap("");
}
((HtmlControl)Master.FindControl("myBody")).Attributes.Add("onload", "GenerateMap()");
}
And in .aspx page
<script type="text/javascript">
var geocoder;
var map = null;
var lat, lng;
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
function GenerateMap() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
var myOptions = {
zoom: 8,
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);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
getHiddenValues();
for (var i = 0; i < lat.length-1; i++) {
var point = new google.maps.LatLng(lat[i], lng[i]);
var marker = createMarker(point,'<div style="width:240px">Address: <br /> City: <br /> State: <br /> Lat n Lng: '+lat[i]+ ', ' +lng[i]+'<\/div>')
}
}
function createMarker(latlng, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
}
function getHiddenValues()
{
lat = document.getElementById("ctl00_ContentPlaceHolder1_hfLat").value.split(',');
lng = document.getElementById("ctl00_ContentPlaceHolder1_hfLng").value.split(',');
}
</script>

Resources