Google Maps API - External link to map markers and open infowindow - google-maps-api-3

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

Related

ionic for multi marker google map opens last markup

I am using ionic to display benefits data on Google map. It works fine except on click of any marker, it opens the last markup content. Follownig is my google map js code
.controller('BenefitsMapCtrl', function ($scope, LocationBenefits, Utilities, $ionicLoading, $compile) {
$scope.init = function () {
var userId = Utilities.getUserId();
LocationBenefits.getLocationBenefits(userId, function (userBenefits) {
console.log("Got location benefits data for Google mp for user id "+userId);
$scope.userBenefits = userBenefits;
var centerLatlng;
if (typeof $scope.userBenefits !== "undefined" && $scope.userBenefits.length > 0) {
var firstBenefitLocation = $scope.userBenefits[0];
centerLatlng = new google.maps.LatLng(firstBenefitLocation.location.lat, firstBenefitLocation.location.lng);
}
var mapOptions = {
center: centerLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
$scope.markers=[];
//Loop in each benefits and place on Google map
if (typeof $scope.userBenefits !== "undefined" && $scope.userBenefits.length > 0) {
for (var i = 0; i < $scope.userBenefits.length; i++) {
var benefit = $scope.userBenefits[i];
//Marker + infowindow + angularjs compiled ng-click
var contentString = "<div><div><img class='shop-icon' src='" + benefit.shopicon + "' alt='" + benefit.shopName + "'/><span class='item-text-wrap'>" + benefit.shopName + "</span></div><div class='shop-offer'>"+benefit.benefits.short_benefitText+"</div><div class='card'><img class='card-art' src='"+benefit.cardart+"' alt='"+benefit.card+"'/></div></div>";
var compiled = $compile(contentString)($scope);
var infowindow = new google.maps.InfoWindow({
content: compiled[0]
});
//Get location
var locationLatLng = new google.maps.LatLng(benefit.location.lat, benefit.location.lng);
var marker = new google.maps.Marker({
position: locationLatLng,
map: map,
title: benefit.shopName
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
$scope.markers.push(marker);
}
}
//Finally set the map
$scope.map = map;
});
};
// google.maps.event.addDomListener(window, 'load', initialize);
$scope.centerOnMe = function () {
if (!$scope.map) {
return;
}
$scope.loading = $ionicLoading.show({
content: 'Getting current location...',
showBackdrop: false
});
navigator.geolocation.getCurrentPosition(function (pos) {
$scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
$scope.loading.hide();
}, function (error) {
alert('Unable to get location: ' + error.message);
});
};
$scope.clickTest = function () {
alert('Example of infowindow with ng-click')
};
});
Issue: On click of any markup on Google map, it always opens the last markup.
Please help.
I had the same problem and spend a lot of time to figure out what's going on so I'd like to add the answer for the future generations,lol.
First of all it's a good idea to refer to official Google maps API docs and take a look at "Events section". I found there one interface of adding event listeners to markers that I never seen before(even after googling this issue for few hours).
marker.addListener('click', function() {});
google.maps.event.addListener(marker, 'click', function () {});
It pointed me out to the idea that when you are trying to do it in the loop using an "old" way, your marker variable is obviously equals to the last element of your markers array. And when event really can be triggered your initialization process is finished what means that your variable has always wrong value in anonymous function at the moment it can be really called. So, again, you didn't passed marker as a parameter to that anonymous event handler.
But you still can do what you want. Just use this.inside your event handler. Bellow is my code sample
marker.addListener('click', function() {
var it = this;
$scope.$apply(function() {
$scope.activeEvent = EventService.getShort($scope.events[it.id]);
});
});
I believe that you can try to use this. in "old-style" interface as well.
I had the same problem and I found the solution here. Apparently, you just have to create a function to create the markers and call that function inside the for loop:
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
$scope.map = map; //Attach the map to the scope before adding the markers
$scope.markers=[];
var infowindow = new google.maps.InfoWindow();
var createMarkers = function (benefit){
//Info window's content
var contentString = "<div><div><img class='shop-icon' src='" + benefit.shopicon + "' alt='" + benefit.shopName + "'/><span class='item-text-wrap'>" + benefit.shopName + "</span></div><div class='shop-offer'>"+benefit.benefits.short_benefitText+"</div><div class='card'><img class='card-art' src='"+benefit.cardart+"' alt='"+benefit.card+"'/></div></div>";
var compiled = $compile(contentString)($scope);
//Get location
var locationLatLng = new google.maps.LatLng(benefit.location.lat, benefit.location.lng);
//Create marker
var marker = new google.maps.Marker({
position: locationLatLng,
map: map,
title: benefit.shopName
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(compiled[0]);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
//Loop in each benefits and place on Google map
if (typeof $scope.userBenefits !== "undefined" && $scope.userBenefits.length > 0) {
for (var i = 0; i < $scope.userBenefits.length; i++) {
var benefit = $scope.userBenefits[i];
createMarkers(benefit);
}
}

new info window does not work when i click on google map marker

Hello i am having problem to show new infowindow when i click on marker.I want to show infowindow after click on marker. Please someone one give me a solution. My code is given bellow.
var markerClusterer = null;
var map = null;
function refreshMap() {
if (markerClusterer) {
markerClusterer.clearMarkers();
}
var markers = [];
var style = parseInt(document.getElementById('style').value, 10);
if (style == 0) {
var data =w_plaza;
var imageUrl = 'images/walton.png';
}
if (style == 1) {
var data =w_dealer;
var imageUrl = 'images/people35.png';
}
if (style == 2) {
var data =w_service_center;
var imageUrl = 'images/service_center.png';
}
var markerImage = new google.maps.MarkerImage(imageUrl);
// var markerImage = new google.maps.MarkerImage(imageUrl,
//new google.maps.Size(24, 32));
for (var i = 0; i < data.length; i++) {
var loc = data[i];
var latLng = new google.maps.LatLng(loc[1],loc[2]);
var content = loc[0] + ":" + loc[1] + "," + loc[2];
var marker = new google.maps.Marker({
position: latLng,
draggable: true,
icon: markerImage
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent("hello");
infowindow.open(map, marker);
});
markers.push(marker);
}
The first time we see infowindow in your code is at:
infowindow.setContent("hello");
What is infowindow, where was it created? Nowhere as far as I can see. Somewhere in your function, before we get as far as creating the marker, create it something like this:
var infowindow = new google.maps.InfoWindow();

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

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

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