Adding markers to google map on button click - javascript

I have following code where I am using a Google map with overlay images. I have hard-coded one marker on this map. In my page, I need to add markers on 'Add Marker' button click getting Latitude and Longitude inputs. How can I push markers on to the map on this button click.
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-map/3.0-rc1/jquery.ui.map.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<style>
#map {
height: 90%;
}
html, body {
height: 90%;
margin: 0;
padding: 0;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?key= xxx"></script>
<script>
var overlay;
MapOverlay.prototype = new google.maps.OverlayView();
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 9.877717, lng: 79.694586},
mapTypeId: 'satellite'
});
var myLatLng = {lat: 9.8, lng: 79.9};
//adding a marker
var marker = new google.maps.Marker({
position: myLatLng,
map: map
});
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(9.71088992, 79.6855391),
new google.maps.LatLng(9.9351849, 80.048088));
var srcImage = 'file:///home/../abc.jpg';
overlay = new MapOverlay(bounds, srcImage, map);
}
function MapOverlay(bounds, image, map) {
........
}
MapOverlay.prototype.onAdd = function() {
.............
};
google.maps.event.addDomListener(window, 'load', initMap);
</script>
</head>
<body>
Latitude : <input type="text" placeholder="Latitude" id="lat"/>
Longitude : <input type="text" placeholder="Longitude" id="lng"/>
<button type="button" id="addMarkerBtnId">Add Marker</button>
<br/><br/>
<div id="map"></div>

One option is to use the google.maps.event.addDomListener function:
google.maps.event.addDomListener(document.getElementById('addMarkerBtnId'), 'click', function(evt) {
var marker = new google.maps.Marker({
position: {
lat: parseFloat(document.getElementById('lat').value),
lng: parseFloat(document.getElementById('lng').value)},
map: map
});
});
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {
lat: 9.877717,
lng: 79.694586
},
mapTypeId: 'satellite'
});
var myLatLng = {
lat: 9.8,
lng: 79.9
};
//adding a marker
var marker = new google.maps.Marker({
position: myLatLng,
map: map
});
google.maps.event.addDomListener(document.getElementById('addMarkerBtnId'), 'click', function(evt) {
var marker = new google.maps.Marker({
position: {
lat: parseFloat(document.getElementById('lat').value),
lng: parseFloat(document.getElementById('lng').value)
},
map: map
});
});
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
Latitude :
<input type="text" placeholder="Latitude" id="lat" value="9.877" /> Longitude :
<input type="text" placeholder="Longitude" id="lng" value="79.694" />
<button type="button" id="addMarkerBtnId">Add Marker</button>
<br/>
<br/>
<div id="map"></div>

Related

How to show two maps in a single page

I tried to add two google maps on single page of my website, but it displays on existing map. How to add two google maps one by one on singe page?
here is the code....
<div class="map">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<div style="overflow:hidden;height:500px;width:1600px;">
<div id="gmap_canvas" style="height:400px;width:1130px;">
</div>
<style>
#gmap_canvas img {
max-width: none!important;
background: none!important
}
</style>
<script type="text/javascript">
function init_map() {
var myOptions = {
zoom: 18,
center: new google.maps.LatLng(10.968203873914659, 79.39677137070021),
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(10.968203873914659, 79.39677137070021)
});
infowindow = new google.maps.InfoWindow({
content: "<b>Code Shoppy</b><br/>Vatti pilaiyar Koil Road<br/>Upstairs of Chola Ceramics<br/>Kumbakonam-612001"
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>
</div>
</div>
<div class="container">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<div style="overflow:hidden;height:500px;width:600px;">
<div id="gmap_canvas" style="height:500px;width:600px;"></div>
<style>
#gmap_canvas img {
max-width: none!important;
background: none!important
}
</style>
<script type="text/javascript">
function init_map() {
var myOptions = {
zoom: 16,
center: new google.maps.LatLng(10.7904833, 78.70467250000002),
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(10.7904833, 78.70467250000002)
});
infowindow = new google.maps.InfoWindow({
content: "<b>Power Integrated Solutions</b><br/>10A/3 Radhkrishnan Colony, Sasthri Road,<br/> Trichy-17"
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
nfowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>
</div>
</div>
</div>
You have two divs with id="gmap_canvas"
id's MUST be unique in HTML or bad things happen
There are some issues with your code:
you're loading the Google maps API twice, which is not necessary
using the same id id="gmap_canvas" for both maps
definig the function init_map twice
I modified your code assigning id="gmap_canvas2" to the second map, calling the init function for the second map init_map2 and loading the Google maps Javascript only once at the beginning.
function init_map() {
var myOptions = {
zoom: 18,
center: new google.maps.LatLng(10.968203873914659, 79.39677137070021),
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById("gmap_canvas2"), myOptions);
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(10.968203873914659, 79.39677137070021)
});
infowindow = new google.maps.InfoWindow({
content: "<b>Code Shoppy</b><br/>Vatti pilaiyar Koil Road<br/>Upstairs of Chola Ceramics<br/>Kumbakonam-612001"
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', init_map);
function init_map2() {
var myOptions = {
zoom: 16,
center: new google.maps.LatLng(10.7904833, 78.70467250000002),
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(10.7904833, 78.70467250000002)
});
infowindow = new google.maps.InfoWindow({
content: "<b>Power Integrated Solutions</b><br/>10A/3 Radhkrishnan Colony, Sasthri Road,<br/> Trichy-17"
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', init_map2);
#gmap_canvas img {
max-width: none!important;
background: none!important
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
First map
<div class="map">
<div style="overflow:hidden;height:500px;width:1600px;">
<div id="gmap_canvas" style="height:400px;width:1130px;">
</div>
</div>
</div>
Second map
<div class="container">
<div style="overflow:hidden;height:500px;width:600px;">
<div id="gmap_canvas2" style="height:500px;width:600px;"></div>
</div>
</div>

Drag marker on Google maps and receive its updated position [duplicate]

I have made a Google Version 3 Geocoder , I want to be able to pick up the coordinates of the marker when it is dragged or clicked. Below is my code:
<!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 JavaScript API v3 Example: Geocoding Simple</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script src="http://maps.google.com/maps/api/js?v=3.5&sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
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,
draggable: true,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
<style type="text/css">
#controls {
position: absolute;
bottom: 1em;
left: 100px;
width: 400px;
z-index: 20000;
padding: 0 0.5em 0.5em 0.5em;
}
html, body, #map_canvas {
margin: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body onload="initialize()">
<div id="controls">
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map_canvas"></div>
</body>
</html>
I have tried to use the following code to do this but it does not seem to work.
// Javascript//
google.maps.event.addListener(marker, 'dragend', function(evt){
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});
google.maps.event.addListener(marker, 'dragstart', function(evt){
document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});
map.setCenter(marker.position);
marker.setMap(map);
//HTML//
<div id='map_canvas'></div>
<div id="current">Nothing yet...</div>
That code works just fine if you put it in the correct place:
http://www.geocodezip.com/BlakeLoizides_geocode.html
(inside the callback routine, the marker is local to it)

google maps api geolocation and place search

I want to include Google Maps in my Web App, for that I´m using google maps API.
I am including both place search and geolocation on the map (I have a button for geolocation), but I noticed place search is not working once I pressed the geolocation button, Place Search doesn´t work.
Any ideas?
here is my code
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="theme.css">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<style type="text/css" media="screen">
</style>
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
#target
{
width: 10%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
/*map*/
// Enable the visual refresh
google.maps.visualRefresh = true;
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
/*map end*/
/*search*/
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds);
var input = /** #type {HTMLInputElement} */(document.getElementById('target'));
var searchBox = new google.maps.places.SearchBox(input);
var markers = [];
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
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(25, 25)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
/*end search*/
</script>
<script>
/*geolocation*/
var map;
function geolocate() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
/*/geolocation*/
</script>
</head>
<body>
<!--search dialog-->
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$( "#dialog-message" ).dialog({ autoOpen: false });
$(' #dialog-message ').dialog({dialogClass:'search'});
$( "#dialog-message" ).dialog({
modal: true,
});
});
</script>
<style type="text/css" media="screen">
.search { background:rgba(240, 255, 255, 0.4);}
.ui-widget-header {font-family: source sans pro; background: white; border: none; border-radius: 0px}
.pac-container {font-family: source sans pro !important; font-size: 20px !important; min-height: 20% !important}
</style>
<div style="font-family: source sans pro;" id="dialog-message" title="Download complete" class="draggable" >
<p>
<div id="panel" width="100%" height="100%">
<input type="text" id="target" placeholder="Search Box" style="width: 100%; font-family: source sans pro; font-size: 20px; height: auto">
</div>
</div>
<!--/search dialog-->
<table>
<div id="map-canvas"></div>
<table id="commandbar" width="100%" height="5%" cellspacing="0" valign="center" style="background-color:rgba(240, 255, 255, 0.4) ;position:fixed; bottom:0;">
<tr height="2.5%">
<td width="2.5%" height="2.5%" >
<img src="browser_resources/close.png" class="button" onclick="window.close()" width="10em">
</td>
<td width="2.5%" height="2.5%" >
<img src="browser_resources/new_window.png" class="button" onclick="window.open('maps.html','_blank', 'location=no, menubar=no, status=no, titlebar=no' )" width="100%">
</td>
<td width="1px"></td>
<td width="1px" id="divider" bgcolor="#999999">
</td>
<td width="1px"></td>
<td width="2.5%">
<img src="maps_resources/Search.png" class="button" onclick="$( '#dialog-message' ).dialog( 'open' ); " width="100%">
</td>
<td width="2.5%">
<img src="maps_resources/Search.png" class="button" onclick="geolocate()" width="100%">
</td>
<td width="95%"></td>
</tr>
</table>
</body>
</html>
You are overwriting the visible map inside geolocate with a new Maps-instance. But the Maps-instance used for the places-related code is still the instance created in initialize(which still exists as an object, but is no longer bound to map you see). Therefore your places-code still works, but you don't see any changes.
Solution: instead of creating a new Maps-instance inside geolocate make the Maps-instance created inside initialize global accessible(by removing the var-keyword)
remove the var-keyword inside initialize():
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
Note: you've defined the function initialize() 2 times, only the 2nd function is important here, the first function will be overwritten.
Remove this from geolocate() map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
Also remove this from the document:<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"><script>It's not the issue here, but there may occur problems when you include the API-script multiple times

Placing a marker in Google maps

So I am preparing a page which has a Google Map and there are two forms namely latitude and longitude , and a submit button.
On entering the longitude and latitude the map is centered to the desired location and puts a marker there.
The problem I am facing is that whenever I put a new lat/long , the old marker won't go.
So basically if entered first lat/long : 10/12 , it would center to that and place a marker there, but when i enter the second lat/long (say) : 11/12 , it would center to that too and place a marker there also while the first one is not removed.
I want the page to be whenever the a new entered in the form only that one reflects in the form no old markers.
Here's my CODE :
<!DOCTYPE html>
<html>
<head>
<title>Google Maps</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(11.6667,76.2667),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
function pan() {
var panPoint = new google.maps.LatLng(document.getElementById("lat").value, document.getElementById("lng").value);
map.setCenter(panPoint)
var marker = new google.maps.Marker({
map: map,
position: panPoint,
});
}
</script>
</head>
<body>
Latitude:<input type="text" id="lat" >
Longitude:<input type="text" id="lng">
<input type="button" value="updateCenter" onclick="pan()" />
<div id="map-canvas"></div>
</body>
</html>
Some help would be useful
You need to clear markers each time in order to do that.
To clean marker keep marker as global variable, eg.
function pan() {
try{
marker.setMap(null);//clear marker
}
catch(err){
}
var panPoint = new google.maps.LatLng(document.getElementById("lat").value, document.getElementById("lng").value);
map.setCenter(panPoint)
//declare marker as global variable
marker = new google.maps.Marker({
map: map,
position: panPoint,
});
}
That should do the trick.
use this code
<!DOCTYPE html>
<html>
<head>
<title>Google Maps</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
var markersArray=[];
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(11.6667,76.2667),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
function pan() {
deleteOverlays();
var panPoint = new google.maps.LatLng(document.getElementById("lat").value, document.getElementById("lng").value);
map.setCenter(panPoint)
var marker = new google.maps.Marker({
map: map,
position: panPoint,
});
markersArray.push(marker);
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
</head>
<body>
Latitude:<input type="text" id="lat" >
Longitude:<input type="text" id="lng">
<input type="button" value="updateCenter" onclick="pan()" />
<div id="map-canvas"></div>
</body>
</html>
In the pan function before adding the new marker, try to remove all the present markers Google Maps API v3: How to remove all markers?

Center marker in Google Maps

I am trying to center a Google map in an iframe. The code below is the content of the iframe.
The marker is not in the center of the frame.
What is missing?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=MYAPIKEY&sensor=false"></script>
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng('<?php echo $this->uri->segment(5); ?>', '<?php echo $this->uri->segment(4); ?>');
var myOptions = {
zoom: 8,
mapTypeControl: false,
scaleControl: false,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
}
initialize();
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
UPDATE
I think I have solved it buy setting a fixed size for the map_canvas instead of using 100%.
I works much better now.
Your code works for me -> http://jsfiddle.net/yRHJv and in jsfiddle the map is inside of iframe.
I have replaced your PHP code with some dummy data.

Categories