I am having a problem deleting user added markers upon a new marker being add. I originally tried to go about the right click method but I only want the user to be able to create one marker at a time. Can someone please help me?
function addMarker(location){
marker = new google.maps.Marker({
position: location,
map: GlobalMap,
draggable: true,
animation: google.maps.Animation.DROP,
clickable: true
});
var form = $("#form").clone().show();
var contentString = form[0];
infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function(){
infowindow.open(GlobalMap,this);
});
infowindow.open(GlobalMap,marker);
markerPosition = marker.getPosition();
populateInputs(markerPosition);
google.maps.event.addListener(marker, "dragend", function (mEvent){
populateInputs(mEvent.latLng);
});
google.maps.event.addListener(marker, 'rightclick', function(){
marker.setMap(null)
});
}
google.maps.event.addDomListener(window, 'load', window.onload);
function populateInputs(pos){
document.getElementById("latitude").value=pos.lat()
document.getElementById("longitude").value=pos.lng();
}
function clearOverlays(){
for(var i = 0; i <markers.length; i++){
markers[i].setMap(null);
}
}
var markers= [];
var center= null;
var GlobalMap = null;
var marker = null;
var infowindow;
var geocoder = new google.maps.Geocoder();
window.onload = function() {
// Creating a reference to the mapDiv, which is defined in the host html file
var mapDiv = document.getElementById('map');
// Creating a latLng for the center of the map, these coordinates set the center of the initial map to the center of Springfield.
var latlng = new google.maps.LatLng(37.1950, -93.2861);
// Creating an object literal containing the properties
// we want to pass to the map
var options = {
center: latlng,
zoom: 11, // This zoom level shows the OTO area.
mapTypeId: google.maps.MapTypeId.ROADMAP // We want to show the data on the road map, as opposed to the satellite view.
};
// Now Creating the map
GlobalMap = new google.maps.Map(mapDiv, options);
oto.setMap(GlobalMap);
$('#address').keypress(function(e){
if(e.which==13){
e.preventDefault();
window.geocode();
}
});
markers.push(marker);
google.maps.event.addListener(GlobalMap, "click", function (event)
{
addMarker(event.latLng);
});
google.maps.event.addListener(marker, 'dragend', function(marker){
var latLong = marker.latLng;
$latitude.value = latLong.lat();
$longitude.value = latLong.lng();
});
}
Here is the HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Public Comment</title>
<link type="text/css" href="css/style.css" rel="stylesheet" media="all" />
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=drawing&sensor=false"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
var otoTableId = '1gPq1ryMpY1S_ovp6pIl0LvqDJkGNUUGShPpDCxtj';
var GlobalMap = null;
//var Urbanlayer = new google.maps.KmlLayer('http://www.ozarkstransportation.org/GIS/OTOBoundary.kml',{preserveViewport:true, suppressInfoWindows:true});
</script>
<script type="text/javascript" src="js/map.js"></script>
</head>
<body>
<!-- Top Banner Bar !-->
<button onclick="toggle_visibility('checkboxes')" style="float: right;">Toggle legend</button>
<div id="banner"><img src="http://www.ozarkstransportation.org/GIS/OTOgraphicSmall.jpg" border="none" height= "66">
<input type="text" id="address" class="form-control" placeholder="e.g., 205 Park Central East, Springfield MO" size="35">
<span class="input-group-btn">
<button onClick="window.geocode()" class="btn btn-success" value=>
<span class="glyphicon glyphicon-map-marker"></span>Go
</button>
</span>
<em id = "banner_text" align="absmiddle">Left click to drop a marker.<br> Right click to delete most recent marker.<br>Cancel to reset with no markers.</em>
</div>
<!-- The Google Map Window !-->
<div id="map"></div>
<!-- The Layer Toggle Window !-->
<div id="checkboxes">
<h3>Left click to drop a marker.<br> Right click to delete marker.<br>Cancel to reset with no markers.</h3>
<br><input type="checkbox" id="NAME" checked="true" onClick="toggleOto()"/><i class="fa fa-minus"></i>OTO Boundary<br />
<table bgcolor="#FFFFFF"><tr><td>
<br>
<!-- <center><b><font color="#000000">Use "add a marker" tool to leave comment.<br> Drag marker to desired location.</font></b></center> !-->
<br>
<center><font size="-1">
OTO MPO |
<!-- #BeginDate format:Am1 -->August 20, 2015<!-- #EndDate --> |
<a target="_blank" href="http://www.ozarkstransportation.org/GIS/Disclaimer.pdf">Disclaimer</a>
</font><br>
<font size="-2">For best results view in Google Chrome</font><br></center>
</td></tr></table>
</div>
<!-- The Bottom Messaging !-->
<div id="container">
</div>
<div id="entryform">
<form role="form" id = "form">
<iframe id ="myFrame" src="https://docs.google.com/forms/d/1EjeuI7ddocJIUr8RALi_WZIuqgQlfgVG9WMqvKR0lSw/viewform?embedded=true" width="500" height="500" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
<h4>Please copy and paste the Latitude and Longitude values into the above form.</h4>
<div class="form-group">
<label><b>Latitude</b></label>
<input id ="latitude" type="text" class="form-control" name="lat" `enter code here`placeholder="Latitude" required="yes">
</div><br>
<div class="form-group">
<label><b>Longitude</b></label>
<input id ="longitude" type="text" class="form-control" name="lng" placeholder="Longitude" required="yes">
</div><br>
<div class="form-group">
<!-- <button class="btn btn-primary" id="submit-button">Submit</button> !-->
<button class="btn btn-primary" id ="delete-button">Cancel</button>
</div>
</form>
</div>
</body>
</html>
Looks like your marker is already global. This should work:
function addMarker(location){
// check if the marker already exists and has a .setMap method
if (marker && marker.setMap) {
// remove existing marker from the map
marker.setMap(null);
}
// create the marker
marker = new google.maps.Marker({
position: location,
map: GlobalMap,
draggable: true,
animation: google.maps.Animation.DROP,
clickable: true
});
// ... rest of your code
Related
so I'm trying to make a Google maps app for Android with Phonegap where I could add markers that have like a message. And the message is just stored locally for now. So I included a picture how the app looks now. Here is the App
So osoite means address, Viesti means message and lisää merkintä means add a note.
So here is the HTMl code for the index:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link rel="stylesheet"
href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-2.1.4.js"
integrity="sha256-siFczlgw4jULnUICcdm9gjQPZkw/YPDqhQ9+nAOScE4="
crossorigin="anonymous"></script>
<script
src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<title>Kartta</title>
</head>
<body>
<div id="pageOne" data-role="page">
<div data-role="header">
<h1>Kartta</h1>
</div>
<div role="main" class="ui-content ui-body-a">
<div id="geolocation" style="width: 285px; height: 370px;">
</div>
<div role="main" class="ui-content ui-body-a">
<p id="pageOne">
</p>
</div> <!-- /content -->
</div>
<div data-role="footer">
<label for="textinput-hide" class="ui-hidden-accessible">Osoite</label>
<input type="text" class="Osoite" name="textinput-hide" id="textinput-hide" placeholder="Osoite"
<br>
<label for="textinput-hide" class="ui-hidden-accessible">Viesti</label>
<input type="text" class="Viesti" name="textinput-hide" id="textinput-hide" placeholder="Viesti">
<br>
<button class="ui-btn">Lisää merkintä</button>
</div> <!-- /footer -->
</div>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=(My own key)">
</script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
$(document).on("pageOne", "#marker", function () {
$.ajax({
url: "https://maps.googleapis.com/maps/api/geocode/json?address=1600+Ratapihantie,+Pasila,+FI&key=(My own key)",
datatype: "json",
timeout: 5000
})
.done(function(data) {
var marker= results[0].geometry.location.lat
var marker2= results[0].geometry.location.lng
})
});
app.initialize();
</script>
</body>
</html>
And here is the code for the Javascript:
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online',
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
// The scope of 'this' is event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
app.receivedEvent('deviceready');
// Get our current location
navigator.geolocation.getCurrentPosition(app.onSuccess, app.onerror);
},
// Current location was found
// Show the map
onSuccess: function(position) {
var longitude = position.coords.longitude;
var latitude = position.coords.latitude;
var latLong = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
center: latLong,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("geolocation"), mapOptions);
},
// Current location could not be determined
// Show error
onerror: function(error) {
alert('code: ' +error.code + '/n' + 'message: ' + error.message + '\n');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
I just need help with adding the marker with the message.
You can use Google Map API for adding markers in map.
For simple marker, use this code:
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
For more details, Check out:
https://developers.google.com/maps/documentation/javascript/examples/marker-simple
I am newbie in Angularjs and I am trying to work on a google maps application using Angularjs. I am able to generate the expected results apart from one thing. When I included {{loc.co1}} to be printed as a table column. It is not showing the result and giving a null. I searched a lot and found that my appraoch is correct. The results are available in the javascript but then when accessing from html, they dont show up. Could you please help me with this.
The input is when we drawing a rectangle on the map and click on submit, the coordinate values should go into the table.
Also, below is a link of the work I did. Sorry for not following the format properly.
http://plnkr.co/edit/kh5cUJabvG2rPJUEbgyt?p=info
===========code ===================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="ISO-8859-1">
<title>Scientist Entry Map</title>
<link rel="stylesheet" href="ScientistMapPage.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" integrity="sha384-3ceskX3iaEnIogmQchP8opvBy3Mi7Ce34nWjpBIwVTHfGYWQS9jwHDVRnpKKHJg7" crossorigin="anonymous"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDVgNI2snXEm8Cu5y-dxk0Y1ep9Iv3SOC4&libraries=drawing,geometry,places" async defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
<!-- <script type="text/javascript" src="lodash.min.js"></script> -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<!-- <script src="https://code.angularjs.org/1.4.8/angular-route.min.js"></script> -->
<!-- <script type="text/javascript" src="angular.min.js"></script> -->
<!-- <script type="text/javascript" src="angular-google-maps.min.js"></script> -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-google-maps/2.3.3/angular-google-maps.min.js"></script> -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="ng-map.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="MapController" class="form-control">
<table>
<tr><td><h1>Map for selecting places</h1></td></tr>
<tr><td>
<input id="placeSearch" class="form-control" type="text" placeholder="Search Box">
<div id="map"></div>
<button class="btn btn-primary" type="reset" id="btnResetRect" placeholder="ResetMap">Reset Map</button>
<button class="btn btn-primary" type="submit" id="btnSubmitRect">Submit Location</button>
<input type="hidden" id="txtCoords">
<input type="text" id="text" value="{{locationsData[0].co1}}"/>
</td>
<td>
<table class="table table-striped table-bordered">
<tr>
<th>Place
</th>
<th>Coordinates-1
</th>
<th>Coordinates-2
</th>
<th>Coordinates-3
</th>
<th>Coordinates-4
</th>
<th>Delete</th>
</tr>
<tr ng-repeat="loc in locationsData">
<td>to be added</td>
<td>{{loc.co1}}</td>
<td>{{loc.co2}}</td>
<td>{{loc.co3}}</td>
<td>{{loc.co4}}</td>
<td><button type="submit" class="btn btn-primary" id="deleteLocation">Delete</button></td>
</tr>
</table>
</td></tr>
</table>
</div>
</body>
</html>
// Code goes here
var myApp = angular.module('myApp',[]);
myApp.controller('MapController',function($scope) {
$scope.rectShape;
$scope.locationsData =[];
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(25, 80),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
$scope.drawingMg = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
//google.maps.drawing.OverlayType.MARKER,
//google.maps.drawing.OverlayType.CIRCLE,
google.maps.drawing.OverlayType.POLYGON,
//google.maps.drawing.OverlayType.POLYLINE,
google.maps.drawing.OverlayType.RECTANGLE
]
},
polygonOptions: {
fillColor: '#BCDCF9',
fillOpacity: 0.5,
strokeWeight: 2,
strokeColor: '#57ACF9',
clickable: false,
editable: true,
draggable : true,
zIndex: 1
},
rectangleOptions:
{
fillColor: 'red',
fillOpacity: 0.5,
strokeWeight: 2,
strokeColor: 'red',
clickable: true,
editable: true,
draggable:true,
zIndex: 1
}
});
var c1,c2,c3,c4;
google.maps.event.addListener($scope.drawingMg, 'rectanglecomplete', function(rectangle) {
//document.getElementById('info').innerHTML += "rectangle points:" + "<br>";
$scope.rectShape= rectangle;
c1 = rectangle.getBounds().getNorthEast().lat() +"," +rectangle.getBounds().getNorthEast().lng();
c2 = rectangle.getBounds().getNorthEast().lat()+"," +rectangle.getBounds().getSouthWest().lng();
c3 = rectangle.getBounds().getSouthWest().lat()+"," +rectangle.getBounds().getNorthEast().lng();
c4 = rectangle.getBounds().getSouthWest().lat()+"," +rectangle.getBounds().getSouthWest().lng();
document.getElementById("txtCoords").innerHTML = c1 +"\n"+c2+"\n"+c3+"\n"+c4;
// alert(document.getElementById("txtCoords").innerHTML.toString());
//document.getElementById("info").innerHTML += ne +"," +sw+ "<br>";
});
$scope.drawingMg.setMap($scope.map);
$scope.clearButton = document.getElementById("btnResetRect");
$scope.map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push($scope.clearButton);
$scope.submitButton = document.getElementById("btnSubmitRect");
$scope.submitButton.onclick = function(){
alert(c1 +""+c2);
//$scope.locationsData =[];
$scope.locationsData.push({
co1 : c1,
co2: c2,
co3: c3,
co4: c4
});
alert($scope.locationsData.length);
// $scope.locationsDatac1 = c1;
// $scope.locationsDatac2 = c2;
// $scope.locationsDatac3 = c3;
// $scope.locationsDatac4 = c4;
alert($scope.locationsData[0].co1);
};
console.log("outside do click");
$scope.clearButton.onclick = function(){
if($scope.drawingMg.getDrawingMode()){
$scope.shape.setMap(null);
//$scope.shape.setBounds(null);
//$scope.drawingMg.getDrawingMode().setMap(null);
}
};
$scope.placeSearch = document.getElementById("placeSearch");
$scope.searchBox = new google.maps.places.SearchBox($scope.placeSearch);
$scope.map.controls[google.maps.ControlPosition.TOP_LEFT].push($scope.placeSearch);
$scope.map.addListener('bounds_changed', function () {
$scope.searchBox.setBounds($scope.map.getBounds());
});
$scope.markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
$scope.searchBox.addListener('places_changed', function () {
$scope.places = $scope.searchBox.getPlaces();
if ($scope.places.length == 0) {
return;
}
// Clear out the old markers.
$scope.markers.forEach(function (marker) {
marker.setMap(null);
});
$scope.markers = [];
var center;
$scope.places.forEach(function (place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var 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(25, 25)
};
// Create a marker for each place.
$scope.markers.push(new google.maps.Marker({
map: $scope.map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds = place.geometry.viewport;
} else {
bounds = place.geometry.location;
}
});
$scope.map.fitBounds(bounds);
});
});
You need to use ng-model in input,
<input type="text" id="text" ng-model="location" />
I have made some necessary changes, no it works
DEMO
I have a problem when I try to show two maps in more than a view. I hope you can help me.
I have this HTML code:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script><!-- load angular -->
........
<div class="tab-content">
<!-- HOME PAGE -->
<div id="pois" class="tab-pane fade in active">
<div class="panel-body">
<div class="row">
<div class="col-md-8">
<div >
<!-- MAPA -->
<div class="embed-responsive embed-responsive-4by3 embed-responsive-item" style="margin-bottom: 10px;
min-width: 323px; min-height: 323px" id="map_canvas"></div>
</div>
</div>
........
<!-- SEARCH TAB -->
<div class="panel-body">
<div class="col-sm-6">
<form class="form" role="form">
<div class="form-group">
<input type="text" class="form-control" placeholder="Direccion" ng-model="address"/>
<div class="well">
<b>Latitud: {{latitud}}</b><br>
<b>Logitud: {{longitud}}</b>
</div>
</div>
<button ng-click="sacarDir(address)" type="submit" class="btn btn-primary btn-block">Buscar</button><br>
</form>
<!-- MAPA -->
<div class="embed-responsive embed-responsive-4by3 embed-responsive-item" style="margin-bottom: 10px;
min-width: 323px; min-height: 323px" id="map_canvas2"></div>
</div>
.................
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXX&callback=initMap">
</script>
CONTROLLER JS:
angular.module('userManager',[],function($locationProvider){
$locationProvider.html5Mode(true);
});
var map;
var map2;
.................
function initMap() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: {lat: 40.46366700000001, lng: -3.7492200000000366},
zoom: 6
});
map2 = new google.maps.Map(document.getElementById('map_canvas2'), {
center: {lat: 40.46366700000001, lng: -3.7492200000000366},
zoom: 6
});
$.get('/pois', function(res){
var message=res.message;
if(!res.error){
for(i=0;i<message.length;i++){
var marker = new google.maps.Marker({
position: {lat: message[i].latitud, lng: message[i].longitud},
map: map,
animation: google.maps.Animation.DROP,
title: message[i].nombre
});
// Push marker to markers array
markers.push(marker);
}
}
});
setMarkers(markers);
}
The problem is that the first map (map_canvas) works perfectly, but when I change to the search tab the map doesn't show, only a grey square. Then if I resize the window of explorer I can see the map (map_canvas2) but the other map (map_canvas) stops working. What can I do?
Thanks!!
I am new to angularjs and javascript. I decided to give this project a try to try and get familiar with these technologies.
I am able to get the markers to create on the first page load but when I add a marker or delete a marker it reloads all of the markers that are stored in the database.
I have the refreshPage(); to be able to not have to refresh the page every time a marker is added or deleted but the angular.foreach is causing it to reload every marker including the ones that are shown on the map.
Is there a better method to do this. I tried putting the angular for each in another http.get and then having a createmarker(item) but that did not work. Which would be the best way to handle this an array, another method, or something else?
Any help is appreciated.
controller.js
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function ($scope, $http) {
var count = 1;
$http.get('/locations').success(function (data) {
angular.forEach(data.items, function (item) {
createMarker(item);
});
});
var refreshPage = function() {
$http.get('/locations').success(function (data) {
$scope.items = data.items;
});
$scope.item = "";
};
refreshPage();
$scope.addLocation = function(){
$http.post('/locations', $scope.item);
refreshPage();
};
$scope.removeLocation = function(id){
$http.delete('/locations/'+id).success(function(response){
refreshPage();
});
};
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(41.5, -73),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (info) {
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.lat, info.long),
title: info.city
});
marker.content = '<div class="infoWindowContent">' + info.desc + '</div>';
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
$scope.openInfoWindow = function (e, selectedMarker) {
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
}]);
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&language=en"></script>
<link rel="stylesheet" href="public/css/maps.css">
<title>My Contact Book</title>
</head>
<body ng-controller="AppCtrl">
<div class="container">
<h1>map here</h1>
<div>
<div id="map"></div>
<div id="repeat" ng-repeat="marker in markers | orderBy : 'title'">
<a id="country_container" href="#" ng-click="openInfoWindow($event, marker)">
<label id="names" >{{marker.title}}</label></a>
</div>
</div>
<div>
<h1>My Contact Book</h1>
{{ greeting }}
<table class="table">
<thead>
<tr>
<th>City</th>
<th>State</th>
<th>Description</th>
<th>Latitude</th>
<th>Longitude</th>
<th>Action</th>
<tbody>
<tr>
<td><input class="form-control" ng-model="item.city"></td>
<td><input class="form-control" ng-model="item.state"></td>
<td><input class="form-control" ng-model="item.desc"></td>
<td><input class="form-control" ng-model="item.lat"></td>
<td><input class="form-control" ng-model="item.long"></td>
<td><button class="btn-primary" ng-click="addLocation()">Add Location</button></td>
</tr>
<tr ng-repeat="item in items">
<td>{{item.city}}</td>
<td>{{item.state}} </td>
<td>{{item.desc}} </td>
<td>{{item.lat}}</td>
<td>{{item.long}}</td>
<td><button class="btn btn-danger" ng-click="removeLocation(item.desc)">Delete</button></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-resource.js"></script>
<script src="/controllers/controller.js"></script>
</body>
</html>
You need to remove them before adding more, set to null the map on each one of the markers:
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
chek this link for more information:
https://developers.google.com/maps/documentation/javascript/examples/marker-remove
I have a problem using responsive Google map on my page. I am using Google Map API v3 & bootstrap 3 CSS to make my site mobile first & responsive. I intend to get users address either by using Google places API by automatically filling up the address form or by getting coordinates from the map and GPS.
I am using radio button to enable user to select either of the two options. The address form is selected as default option. When Use Map option is selected, the form has to be hidden & the Google map should be visible in its place but that just won't happen. I used Mozilla's Inspect Element option to check if the map is loaded in the background & yes it did.
The problem:
The map just wont show up on the specified div which is div id="map-canvas" Except that everything works fine, I even managed to get static Google map as image to be displayed in the same div appending the image file to the div using .innerHTML() function.
The solution I need ia to be able to display the map inside the map-canvas div & the map should be responsive.
Here's my code (html + js + css) :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Address form</title>
<!-- Bootstrap Core CSS -->
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<!--Start of CSS for Google Places API-->
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<style>
#locationField{
position: relative;
}
</style>
<!--End of assets for G Places API-->
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body onload="initialize()">
<div class="container">
<div>
<legend>Address</legend>
</div>
<form class="form-horizontal" action="" method="POST">
<fieldset>
<div class="well col-md-12">
<h4><strong>Where are you?</strong></h4><br /><br />
<legend></legend>
<div class="col-md-6">
<h4><strong>Your Information</strong></h4>
<legend></legend>
<div class="control-group">
<label class="control-label" for="location">Provide your location:</label>
<div class="controls">
<label class="radio-inline"><input id="loc_method" type="radio" name="loc_method" value="form" class="input-xlarge" checked required>Use Form </label>
<label class="radio-inline"><input id="loc_method" type="radio" name="loc_method" value="map" class="input-xlarge" onClick="getLocation()" required>Use Map </label>
<br />
</div>
</div>
<div class="address-form">
<div class="control-group">
<label class="control-label" for="address">Address</label>
<div class="controls">
<div id="locationField">
<input type="text" id="autocomplete" name="address" placeholder="Enter your address" class="form-control" required>
</div>
</div>
</div>
<br />
<div class="control-group">
<table class="table table-bordered table-hover">
<tr>
<td><label class="control-label">Locality</label></td>
<td><input class="form-control" id="street_number" name="tole" disabled="true"></input></td>
</tr>
<tr>
<td><label class="control-label">Street</label></td>
<td><input class="form-control" name="street" id="route" disabled="true"></input></td>
</tr>
<tr>
<td><label class="control-label">City</label></td>
<td><input class="form-control" id="locality" name="city_vdc" disabled="true"></input></td>
</tr>
<tr>
<td><label class="control-label">Region</label></td>
<td><input class="form-control" name="region" id="administrative_area_level_1" disabled="true"></input></td>
</tr>
<tr>
<td><label class="control-label">Zip code</label></td>
<td><input class="form-control" id="postal_code" name="zip" disabled=""></input></td>
</tr>
<tr>
<td><label class="control-label">Country</label></td>
<td><input class="form-control" name="country" id="country" disabled="true"></input></td>
</tr>
</table>
</div>
</div>
<div class="map-canvas control-group">
<div id="map-canvas">
<!--Map Should Be Here-->
</div>
</div>
</div>
<!-- Button -->
<div class="control-group col-md-12">
<br /><legend></legend>
<div class="controls">
<button type="submit" name="submit" class="btn btn-success pull-right">Submit</button>
<br /><br />
</div>
</div>
</div>
</fieldset>
</form>
</div>
<!--JS for Address Mode Selection-->
<script type="text/javascript">
$("input:radio[name=loc_method]:first-child").click(function(){
if($(this).val()=="form"){
$(".address-form").css("display","block");
$(".map-canvas").css("display","none")
}else{
$(".map-canvas").css("display","block");
$(".address-form").css("display","none");
}
})
</script>
<!--JS API For Google Places Address Form Autofill-->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script type="text/javascript">
var y = document.getElementById("map-canvas");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError,{
enableHighAccuracy: true,
timeout:30000
});
} else {
y.innerHTML = "Geolocation is not supported by this browser, choose <b>Use Form</b> option to fill the address form.";
}
}
function showPosition(position) {
//These commented codes below are to display static GMap of the acquired coordinates as image in the div id="map-canvas" which I did successfully
/*var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=320x240&sensor=true";
y.innerHTML = "<br />Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude +
"<br>Altitude: " + position.coords.altitude +
"<br>Position Accuracy: " + position.coords.accuracy +
"<br>AltitudeAccuracy: " + position.coords.altitudeAccuracy +
"<br><img src='"+img_url+"'>";*/
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map-canvas"),myOptions);
//google.maps.event.addDomListener(window, 'load', initialize);
var point = new google.maps.LatLng(position.coords.atitude, position.coords.longitude);
var marker = new google.maps.Marker({
position:point,
map:map,
title:'Rescue Team Needed Here # <br />' + position.coords.latitude + 'deg. South & <br />' + position.coords.longitude + 'deg. East',
draggable:true,
});
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation. If you are concerned with your privacy choose <b>Use Form</b> option to fill the address form."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable. Choose <b>Use Form</b> option to fill the address form."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out. Choose <b>Use Form</b> option to fill the address form."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred. Choose <b>Use Form</b> option to fill the address form."
break;
}
}
</script>
<script>
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initialize() {
// Create the autocomplete object, restricting the search
// to geographical location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {HTMLInputElement} */(document.getElementById('autocomplete')),
{ types: ['geocode'],
componentRestrictions: {country: 'np'}});
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
// [START region_fillform]
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// [END region_fillform]
// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation]
</script>
Hope this you looking for.. which i understand from your question.
Define width:100%
#map-canvas {
margin: 20px 0;
padding: 0;
height: 300px;
float: left;
width: 100%;
}
HTML CODE
<div class="col-md-12">
<div id="map-canvas" style="position: relative; overflow: hidden; transform: translateZ(0px); background-color: rgb(229, 227, 223);"></div>
</div>
Adding class col-xs-12 to your map div will do the job.
Go ahead re-size the windows, the map will automatically resize, remaining in its div.
.yourdiv {
border: solid;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div class="yourdiv col-xs-12" id="map-canvas"></div>
</body>
</html>