Following is my code which i am using to populate marker from the array address but its not showing any marker nor map to the respective div, Kindly let me know what i did wrong and how can i resolve this issue.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
$(document).ready(function(){
var myOptions = {
center: new google.maps.LatLng(54, -2),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var addressArray = new Array("41 Green Ln, Handsworth, Birmingham, West Midlands B21 0DE, UK","BT27 4SB","Norwich");
var geocoder = new google.maps.Geocoder();
var markerBounds = new google.maps.LatLngBounds();
for (var i = 0; i < addressArray.length; i++) {
geocoder.geocode( { 'address': addressArray[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
markerBounds.extend(results[0].geometry.location);
map.fitBounds(markerBounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
</script>
<div id="map_canvas"></div>
In order for the map to display, you'll need to give #map_canvas an absolute width/height using CSS.
Example fiddle: http://jsfiddle.net/sCvJk/
Related
I am getting an Add Marker is undefined when using this script but I can't seem to figure out the issue. Any suggestions to remedy this error is greatly appreciated:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="map" style="width: 700px; height: 400px"></div>
<script type="text/javascript">
var latlng = new google.maps.LatLng(40.756, -73.986);
var options = {
center : latlng,
zoom : 1,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// Creating the map
var map = new google.maps.Map(document.getElementById('map'), options);
var geocoder = new google.maps.Geocoder();
var marker= new google.maps.Marker(null);
function AddMarker(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 });
var infowindow;
if (!infowindow)
{
infowindow = new google.maps.InfoWindow();
}
infowindow.setContent(address);
google.maps.event.addListener(marker, 'click', function()
{
infowindow.open(map,marker);
});
}
});
}
</script>
It looks like you have called the function "Add Marker" and not "AddMarker(target)"
you call infowindow just right the declaration of it.
It might be that you call AddMarker too early.
https://jsfiddle.net/c472zjqc/
var latlng = new google.maps.LatLng(40.756, -73.986);
var options = {
center: latlng,
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Creating the map
var map = new google.maps.Map(document.getElementById('map'), options);
var geocoder = new google.maps.Geocoder();
var marker = new google.maps.Marker(null);
function AddMarker(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
});
var infowindow;
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
infowindow.setContent(address);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
});
}
AddMarker('Wichita, KS');
map.setZoom(3);
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="map" style="width: 700px; height: 400px"></div>
I'm trying to add a marker using a button in Google Maps and I'm getting the error, cannot read property lat of null. I'm not that good in Javascript, any help?
function setmarker(){
setLatLng = new google.maps.LatLng(document.getElementById('latitude').value,document.getElementById('longitude').value);
alert(setLatLng);
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var mapOptions = {
zoom: 8,
//center: new google.maps.LatLng(-1.2921897,36.8288574)
};
var marker = new google.maps.Marker({
position: setLatLng,
map: map,
title: 'Obtained coordinate'
});
}
</script>
</head>
<body>
<div id="map-canvas"></div>
<div class="side-panel">
<div>Latitude:<br><input type="text" name="latitude" id="latitude" ></div>
<div>Longitude:<br><input type="text" name="longitude" id="longitude"></div><br>
<!-- <input type="submit" onsubmit="setmarker();"> -->
<button onclick="setmarker()">Show Marker</button>
</div>
When you do document.getElementById('latitude').value that returns the value as a string e.g. "51.23546" instead of the floating point number that Google's API expects.
To make sure they get passed to Google as floats, try:
setLatLng = new google.maps.LatLng(
parseFloat(document.getElementById('latitude').value),
parseFloat(document.getElementById('longitude').value)
);
Thanks for all the answers, stumbled upon the answer in the name of Reverse GeoCoding Service from Google that exactly did what I wanted to quite easily and in the exact way.
From the API: https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
var geocoder;
var map;
var infowindow = new google.maps.InfoWindow();
var marker;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: 'roadmap'
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeLatLng() {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I've heard that it is possible to submit an Address instead of Longitude and Latitude and this would be much more feasible for my system. The user has to input their address when creating their profile and their profile afterwards will then display a Google Maps of their house. I currently have the Google Maps API working perfectly with Longitude and Latitude:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="css.css" />
<title>Login Page</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% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MYKEY&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.640143,1.28685),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(52.640143,1.28685),
map: map,
title: "Mark On Map"
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
Please could somebody assist me to alter my code so that it enables the Google Maps API to request an Address in its place because I want to read the Address of the user directly from mySQL database.
See this example, initializes the map to "San Diego, CA".
Uses the Google Maps Javascript API v3 Geocoder to translate the address into coordinates that can be displayed on the map.
<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>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var address ="San Diego, CA";
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
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);
if (geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow(
{ content: '<b>'+address+'</b>',
size: new google.maps.Size(150,50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title:address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%">
</body>
</html>
working code snippet:
var geocoder;
var map;
var address = "San Diego, CA";
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
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);
if (geocoder) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow({
content: '<b>' + address + '</b>',
size: new google.maps.Size(150, 50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
}
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" ></div>
You can parse the geolocation through the addresses.
Create an Array with jquery like this:
//follow this structure
var addressesArray = [
'Address Str.No, Postal Area/city'
]
//loop all the addresses and call a marker for each one
for (var x = 0; x < addressesArray.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addressesArray[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
//it will place marker based on the addresses, which they will be translated as geolocations.
var aMarker= new google.maps.Marker({
position: latlng,
map: map
});
});
}
Also please note that Google limit your results if you don't have a business account with them, and you my get an error if you use too many addresses.
Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map.
Would this be what you are looking for: Contains sample code
https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingRequests
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
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == '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);
}
});
}
<body onload="initialize()">
<div id="map" style="width: 320px; height: 480px;"></div>
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Encode" onclick="codeAddress()">
</div>
</body>
Or refer to the documentation https://developers.google.com/maps/documentation/javascript/geocoding
Thought I'd share this code snippet that I've used before, this adds multiple addresses via Geocode and adds these addresses as Markers...
var addressesArray = [
'Address Str.No, Postal Area/city',
//follow this structure
]
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 12.7826,
lng: 105.0282
},
zoom: 6,
gestureHandling: 'cooperative'
});
var geocoder = new google.maps.Geocoder();
for (i = 0; i < addressArray.length; i++) {
var address = addressArray[i];
geocoder.geocode({
'address': address
}, function(results, status) {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
center: {
lat: 12.7826,
lng: 105.0282
},
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
I have an element on my page which I have assigned the ID 'address' to:
<p id="address">1600 Pennsylvania Ave NW, Washington, DC 20500, United States</p>
Now I am trying to create a Google map from it using the following:
<script type="text/javascript">
var gecoder, map;
var address = document.getElementById('address').innerHTML;
function googlemap(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 8,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
});
}
</script>
However this returns nothing. I get a blank. Any idea what i am doing wrong?
This is what I did and it works. JavaScript in the head:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false" />
<script type="text/javascript">
var geocoder, map;
function googlemap() {
var address = document.getElementById('address').innerHTML;
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myPosition = results[0].geometry.location;
alert(myPosition);
var myOptions = {
zoom: 8,
center: myPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'), myOptions);
var marker = new google.maps.Marker({
map: map,
position: myPosition
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
The body:
<body onload="googlemap()">
<form id="form1" runat="server">
<div>
<p id="address">1600 Pennsylvania Ave NW, Washington, DC 20500, United States</p>
<div id="map" style="overflow:hidden; width:400px; height:400px"></div>
</div>
</form>
I used this example
example to create my code to find an address from lat. and long. coordinates.
The problem is that also with the correct coordinates, I find the postcode and not the address. Instead in the example, it can find the address.
I tried also to use the inverse method. I used coordinates that I found with the address, but they give me the postcode and not the address again.
Where am I wrong?
My code is the following:
<!DOCTYPE html>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<HTML>
<HEAD>
<script type="text/javascript" src="jquery.js"></script>
<META NAME="GENERATOR" Content="AlterVista - Editor HTML">
<title>LowPricePetrol</title>
<link rel="stylesheet" type="text/css" href="homeformat.css"/>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/">
</script>
<script type="text/javascript">
var geocoder;
var map;
var lat_;
var lng_;
var contentString="";
var infowindow = null;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(mia_posizione);
}else{
alert('La geo-localizzazione NON รจ possibile');
}
function initialize() {
infowindow = new google.maps.InfoWindow();
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function mia_posizione(position) {
var lat_gl = position.coords.latitude;
var lon_gl = position.coords.longitude;
var latlng = new google.maps.LatLng(lat_gl , lon_gl );
alert(latlng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert(results[1].formatted_address);
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</HEAD>
<BODY onload="initialize();">
<div class="mapbox" id="map_canvas" style="width:700px; height:350px" ></div>
</BODY>
</HTML>
Below is the complete working example with the DEMO added at JSFIDDLE:
<script type="text/javascript">
function showAddress() {
var map,marker,infoWindow, geocoder;
var markerPoint = new google.maps.LatLng(12.397,78.644);
var mapOptions = {
center: new google.maps.LatLng(12.397,73.644),
zoom:5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
google.maps.event.addListener(map,'click',function(e) {
getAddress(e.latLng);
});
function getAddress(latLng) {
if(!geocoder) {
geocoder = new google.maps.Geocoder();
}
var geocoderRequest = {
latLng:latLng
}
geocoder.geocode(geocoderRequest, function(results, status) {
if(!infoWindow) {
infoWindow = new google.maps.InfoWindow();
}
infoWindow.setPosition(latLng);
var content = "<h2>Position :" +latLng.toUrlValue()+ "</h2>"
if(status == google.maps.GeocoderStatus.OK) {
for(var i =0;i <results.length; i++) {
if(results[0].formatted_address) {
content += i + ". " +results[i].formatted_address + "<br />";
}
}
}
else {
content += "<p>Either you clicked on Ocean or a Politically disputed Area. Status = " + status + "</p>"
}
infoWindow.setContent(content);
infoWindow.open(map)
});
}
}
</script>
DEMONSTRATION
Clicking on a Map will generate an InfoWindow and this infowindow will have the address of the place clicked, based on reverse geocoding.