I am using the the Google Maps JavaScript API v3. I have a map that has markers on each state. When I click the state marker, I need access to the state abbreviation in the callback function. Is there any way native to google maps that I can access the state of a marker?
google.maps.event.addListener(mark,'click',function(event){
// how can I access the state abbreviation (e.g. 'MO') from in here?
}
I know that I can probably accomplish this via reverse geocoding, but is there any simpler (and less error-prone) way?
If this can only be accomplished using reverse geocoding, what is the simplest code to access the state? I assume my code would look something like this:
google.maps.event.addListener(mark,'click',function(event){
geocoder.geocode({'latLng': event.latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
... get state from results ...
}
}
}
What would be the simplest code to get the state from the results? Based on the documentation of the address component types, I assume I would be looking for the "short_name" of the "administrative_area_level_1". Is this correct? Is there an easier way to access it than looping over the results until I find the "administrative_area_level_1"? (I have jquery included on the page and so can code with it if it makes anything simpler)
Here's a working example:
<!DOCTYPE html>
<html>
<head>
<title>http://stackoverflow.com/questions/17144375/how-to-get-the-state-of-a-marker?noredirect=1#comment24816710_17144375</title>
<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%; width:100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var markers = [
{lat:54.60039, lng:-3.13632, state:"AA"},
{lat:54.36897, lng:-3.07561, state:"ZZ"},
];
function initialize() {
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(54.42838,-2.9623),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var marker;
var infowindow = new google.maps.InfoWindow({
content: ''
});
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
for (var i = 0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i].lat,markers[i].lng),
map: map,
title:"marker " + i,
state: markers[i].state // a custom property of our own
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.state);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
Related
I need do embed a kml google earth map in my webpage.
I followed this instructions, but the link to get the code to embed doesn't seem to be activated here.
I also tryed the followning code, but it shows a simple map without the informatons in the kml file
<head>
<title></title>
<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 }
#google-map { height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=MY-KEY&sensor=false">
</script>
<script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(42.753633, 13.952404),
zoom: 10,
mapTypeId: google.maps.MapTypeId.SATELLITE,
scrollwheel: false
}
var map = new google.maps.Map(document.getElementById('google-map'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'poligono1.kml'
});
ctaLayer.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="initialize()">
<div id="google-map" class="google-map"></div>
</body>
i put the kml file in the same folder of the webpage.
Thanks in advance for helping me!!!
i tried the scaisEdge code, and it works fine.
but in iis were missing the mime type, then i added the mime type, and now it works fine... thanks geocodezip!!!
I think this sample from google developer could be useful
<!DOCTYPE html>
<html>
<head>
<style>
#map-canvas {
width: 500px;
height: 400px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
</head>
<body>
<div id="map-canvas"></div>
<script>
/**
* #fileoverview Sample showing capturing a KML file click
* and displaying the contents in a side panel instead of
* an InfoWindow
*/
var map;
var src = 'https://developers.google.com/maps/tutorials/kml/westcampus.kml';
/**
* Initializes the map and calls the function that creates polylines.
*/
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-19.257753, 146.823688),
zoom: 2,
mapTypeId: google.maps.MapTypeId.TERRAIN
});
loadKmlLayer(src, map);
}
/**
* Adds a KMLLayer based on the URL passed. Clicking on a marker
* results in the balloon content being loaded into the right-hand div.
* #param {string} src A URL for a KML file.
*/
function loadKmlLayer(src, map) {
var kmlLayer = new google.maps.KmlLayer(src, {
suppressInfoWindows: true,
preserveViewport: false,
map: map
});
google.maps.event.addListener(kmlLayer, 'click', function(event) {
var content = event.featureData.infoWindowHtml;
var testimonial = document.getElementById('capture');
testimonial.innerHTML = content;
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>
I have one code that shows elevation and another which displays weather information. Is there a way to merge the two codes together so I have one map that has both features? I am using notepad to work on this.
Code 1:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Elevation 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 weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.CELSIUS
});
weatherLayer.setMap(map);
var cloudLayer = new google.maps.weather.CloudLayer();
cloudLayer.setMap(map);
}
var elevator;
var map;
var infowindow = new google.maps.InfoWindow();
var denali = new google.maps.LatLng(60.750000, -139.500000);
function initialize() {
var mapOptions = {
zoom: 8,
center: denali,
mapTypeId: 'terrain'
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Create an ElevationService
elevator = new google.maps.ElevationService();
// Add a listener for the click event and call getElevation on that location
google.maps.event.addListener(map, 'click', getElevation);
}
function getElevation(event) {
var locations = [];
// Retrieve the clicked location and push it on the array
var clickedLocation = event.latLng;
locations.push(clickedLocation);
// Create a LocationElevationRequest object using the array's one value
var positionalRequest = {
'locations': locations
}
// Initiate the location request
elevator.getElevationForLocations(positionalRequest, function(results, status) {
if (status == google.maps.ElevationStatus.OK) {
// Retrieve the first result
if (results[0]) {
// Open an info window indicating the elevation at the clicked position
infowindow.setContent('The elevation at this point <br>is ' + results[0].elevation + ' meters.');
infowindow.setPosition(clickedLocation);
infowindow.open(map);
} else {
alert('No results found');
}
} else {
alert('Elevation service failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
AND Code 2:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Weather layer</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&libraries=weather"></script>
<script>
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(60.750000, -139.500000),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.CELSIUS
});
weatherLayer.setMap(map);
var cloudLayer = new google.maps.weather.CloudLayer();
cloudLayer.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
You would probably want to put the code into a seperate .js file, and link it in. That way, the code would be right next to each other, and hence you could get both effects, which other wise would not work. You are already linking a script file from google - all you would need is to put the code of yours into a .js file, and link it in the same way
*Hi there, i am new to the whole Google map api environment so please do guide me along.
What i am trying to achieve below is to extract data from either a XML file or a JSON file and plot the locations onto Google map. I am also trying to add a info window whereby it will show different information for each location. I understand that to have a info window, i would have to create a over lay. But the question is how do i actually tag multiple info-window to their markers ?
All markers are displayed well on the map, but the problem is when I click to see info window - info window is always displayed on the same marker. What's the problem?
This is what i have came up with so far and i would greatly appreciate if anyone is able to spot the issue.
<!DOCTYPE html>
<html>
<head>
<style>
html, body, #map_canvas { margin: 0; padding: 0; height: 100%; }
</style>
<script
src="https://maps.googleapis.com/maps/api/js sensor=false&libraries=visualization">
</script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(-27.48939, 153.012772),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var script = document.createElement('script');
script.src = 'http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week';
document.getElementsByTagName('head')[0].appendChild(script);
}
window.eqfeed_callback = function(results) {
for (var i = 0; i < results.features.length; i++) {
var earthquake = results.features[i];
var coords = earthquake.geometry.coordinates;
var latLng = new google.maps.LatLng(coords[1],coords[0]);
var marker = new google.maps.Marker({
position: latLng,
map: map,
});
var infowindow = new google.maps.InfoWindow({
content: "<div>Hello! World</div>",
maxWidth:100
});
google.maps.event.addListener(marker, "mouseover", function() {
infowindow.open(map, marker);
});
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
Use this instead of marker, when opening infowindow.
google.maps.event.addListener(marker, "mouseover", function() {
infowindow.open(map, this);
});
brand new here.....don't hurt me :). I also apologize if my terminology is incorrect.
I have no HTML experience but come here via FileMaker. I'm working on a FileMaker database just for my own small business and came across Geocoding, which I added to my database. Everything works fine. But I'm trying to figure out where in the HTML I could change the parameters so when I roll over a marker I can see the Customer's name, and not just "Marker 1". I was able to adjust the document so when I click on the marker, Name, Address, City State, etc. all pop up, but can't seem to figure out the marker (label?) part. If this is too much to ask, I apologize, and could you please just point me in the right direction.
I've been on this site and a few others over the past week, just reading & trying to learn all I can, and tinkering, but still remain stumped.
Any help/direction would be greatly appreciated. Of course if you need any more info just please ask.
Thanks
Steve
PS Please note the below HTML is not something I created, just imported to my DB solution.
<!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 Test</title>
<style type="text/css">
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js? sensor=false"></script>
<script type="text/javascript">
function initialize() {
var myOptions = {
zoom: 5,
center: new google.maps.LatLng(46.52863469527167,2.43896484375),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID]
}
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var markerBounds = new google.maps.LatLngBounds();
var markers = new Array(
[[MarkersArray]]
);
var infoWindow = new google.maps.InfoWindow;
function addMarker(options){
var marker = new google.maps.Marker({map:map});
marker.setOptions(options);
google.maps.event.addDomListener(marker, 'click', function() {
infoWindow.setContent(marker['info']);
infoWindow.open(map, marker);
});
markerBounds.extend(options.position);
return marker;
}
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
var end = markers.length;
for(var i=0; i<end; i++) {
addMarker({
position: markers[i]['position'],
title: "Marker "+i,
info: markers[i]['info']
});
}
map.setCenter(markerBounds.getCenter());
map.fitBounds(markerBounds);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
The "title" of the marker is what is displayed on mouseover. It is being set by this code:
addMarker({
position: markers[i]['position'],
title: "Marker "+i,
info: markers[i]['info']
});
Change the "Marker "+i to be the text you want displayed.
I put there my whole code. Trying to determine location address. My script should create still one marker with geocoded address (in console - variable kktina).
But, unfortunately, there isn't everything OK. Because by script still resolves previous location (or it takes previous coordinates, dunno). Maybe there is an error in code, but I'm not able to do this anymore..
So asking for help, thank you!
<!DOCTYPE html>
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places,geometry"></script>
<script src="http://code.jquery.com/jquery-1.7.min.js" type="text/javascript"></script>
<script>
var map,marker;
var geocoder = new google.maps.Geocoder();
var markers = [];
var img,icon,type;
var prenos,pos,address = "5",point;
function clearMarkersFromArray() {
if (markers.length>0){
markers[0].setMap(null);
markers.shift(markers[0]);
}
}
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
address = responses[0].formatted_address;
} else {
address = 'Cannot determine address at this location.';
}
});
return address;
}
function initialize() {
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(49,19),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions),
google.maps.event.addListener(map, 'click', function(response) {
clearMarkersFromArray();
point = new google.maps.LatLng(response.latLng.$a,response.latLng.ab);
var kktina = geocodePosition(point);
console.log(kktina);
var marker = new google.maps.Marker({
position: point,
draggable: true
});
markers.push(marker)
marker.setMap(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas" style="height:400px;width:700px;"></div>
</body>
</html>
You can't do this:
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
address = responses[0].formatted_address;
} else {
address = 'Cannot determine address at this location.';
}
});
return address;
}
the Geocoder is asynchronous, the value of address is undefined when it is returned.
Use the returned data inside the callback function instead, something like this (not tested):
var kktina = null;
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
kktina = responses[0].formatted_address;
} else {
kktina = 'Cannot determine address at this location.';
}
console.log(kktina);
var marker = new google.maps.Marker({
position: point,
draggable: true
});
markers.push(marker)
marker.setMap(map);
});
}