How to make google map responsive inside any div element? - javascript

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>

Related

Adding Google Maps API to React to calculate route between two points

I'm trying to make an React app, that shows the distance between two points on a map.
I got it to work in Javascript and HTML, but i'm having trouble converting it to React (I'm new).
At first i got an error: 'google' is not defined. i fixed it by adding: const google = window.google;
Now i'm getting these errors:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!-- GOOGLE API -->
<script src="https://maps.googleapis.com/maps/api/js?key=MY_GOOGLE_MAPS_API_KEY&libraries=places"></script>
<!-- BOOTSTRAP -->
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"
></script>
</body>
</html>
App.js:
import logo from "./logo.svg";
import "./App.css";
import GoogleMapsApi from "./GoogleMapsApi";
function App() {
return (
<>
<GoogleMapsApi/>
</>
);
}
export default App;
GoogleMapsApi.js:
import React from "react";
import $ from "jquery";
const google = window.google;
const GoogleMapsApi = () => {
//set map options
// start pos
const myLatLng = { lat: 51.5, lng: -0.1 };
const mapOptions = {
center: myLatLng,
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
//create map
const map = new google.maps.Map(
document.getElementById("googleMap"),
mapOptions
);
//create a DirectionsService object to use the route method and get a result for our request
const directionsService = new google.maps.DirectionsService();
//create a DirectionsRenderer object which we will use to display the route
const directionsDisplay = new google.maps.DirectionsRenderer();
//bind the DirectionsRenderer to the map
directionsDisplay.setMap(map);
//define calcRoute function
function calcRoute() {
//create request
const request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: google.maps.TravelMode.DRIVING, //WALKING, BYCYCLING, TRANSIT
unitSystem: google.maps.UnitSystem.METRIC,
};
//pass the request to the route method
directionsService.route(request, function (result, status) {
if (status === google.maps.DirectionsStatus.OK) {
//Get distance and time
$("#output").html(
"<div class='alert-info'>From: " +
document.getElementById("from").value +
".<br />To: " +
document.getElementById("to").value +
".<br /> Driving distance: " +
result.routes[0].legs[0].distance.text +
".<br />Duration: " +
result.routes[0].legs[0].duration.text +
".</div>"
);
//display route
directionsDisplay.setDirections(result);
} else {
//delete route from map
directionsDisplay.setDirections({ routes: [] });
//center map in London
map.setCenter(myLatLng);
//show error message
$("#output").html(
"<div class='alert-danger'>Could not retrieve driving distance.</div>"
);
}
});
}
const x = document.getElementById("from");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
// Use this to show in app
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
document.getElementById("from").value =
position.coords.latitude + ", " + position.coords.longitude;
}
return (
<>
<div className="App">
<div class="jumbotron">
<div class="container-fluid">
<h1>Distance between cities App.</h1>
<p>Our app will help you calculate travelling distances.</p>
<form class="form-horizontal">
<div class="form-group">
<label for="from" class="col-xs-2 control-label">
From:
</label>
<div class="col-xs-10">
<input
type="text"
id="from"
placeholder="Origin"
class="form-control"
/>
</div>
</div>
<div class="form-group">
<label for="to" class="col-xs-2 control-label">
To:
</label>
<div class="col-xs-10">
<input
type="text"
id="to"
placeholder="Destination"
class="form-control"
/>
</div>
</div>
</form>
{/* GET LOCATION IN LAT AND LONG */}
<div class="col-xs-offset-2 col-xs-10">
{/* Get currnet */}
<button class="btn btn-info btn-lg" onClick={getLocation()}>
Try It
</button>
<p id="demo"></p>
</div>
<div class="col-xs-offset-2 col-xs-10">
<button class="btn btn-info btn-lg" onClick={calcRoute()}>
Submit
</button>
</div>
</div>
<div class="container-fluid">
<div id="googleMap"></div>
<div id="output"></div>
</div>
</div>
</div>
</>
);
};
export default GoogleMapsApi;
Foremost, I would consider using google-map-react instead of using window.google directly.
R.e. your specific error: I suspect your document.getElementById("googleMap") is returning null because <div id="googleMap"></div> won't have been rendered when the GoogleMapsApi component is initialized.
Review State and Lifecycle
, specifically:
The componentDidMount() method runs after the component output has been rendered to the DOM.
Inside componentDidMount() your document.getElementById("googleMap") should return a non-null value.
I also recommend looking at the code for google-map-react to see how it is implemented there.

how to display multiple google maps per page

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!!

Maps markers duplicates appearing because of http.get angular foreach

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

Delete marker when new marker is added?

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

How can I change markers images in this javascript

I want to change Images of my markers in this javascript
can anybody help me out from this?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=abcdefg&sensor=true_or_false"
type="text/javascript"></script>
<script type="text/javascript">
function geocoder(){
var place = document.getElementById("textarea").value;
geocoder = new GClientGeocoder();
geocoder.getLatLng(place, function(point)
{
if (!point)
{
alert(place + " not found");
}
else
{
var info = "<h3>"+place+"</h3>Latitude: "+point.y+" Longitude:"+point.x;
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(point, 13);
map.setUIToDefault();
var marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(point.toUrlValue(5));
}
}
);
}
</script>
</head>
<body>
<table width="347" border="1" align="right">
<tr>
<td width="168"> </td>
<td width="163"> </td>
</tr>
<tr>
<td height="45"><div align="right">Address : </div></td>
<td><form id="form1" name="form1" method="post" action="">
<label>
<textarea name="textarea" id="textarea"></textarea>
</label>
</form>
</td>
</tr>
<tr>
<td><form id="form2" name="form2" method="post" action="">
<label>
<input name="Button" type="Button" id="Button" value="Submit" onClick="geocoder()" onunload="GUnload()"/>
</label>
</form>
</td>
<td> </td>
</tr>
</table>
<div id="map_canvas" style="width: 500px; height: 300px"></div>
</body>
</html>
The GMarker constructor takes a GMarkerOptions as the second parameter. You can use that to specify a GIcon to use for the marker.
It may look something like this:
var marker = new GMarker(point, {
icon: new GIcon(
G_DEFAULT_ICON,
'/images/custom_marker.png')
});
This uses the default icon as a baseline, and changes just the main image. There are a number of other properties you can set on the icon, depending on whether you need to change the shadow, etc.
You can also upload your image to a site, like the Google Map Custom Marker Maker, which will create the extra images and javascript for the icon.
Finally, check out the Custom Icons for Markers topic on the Google Maps group.
You can specify your marker parameters like so:
var num = 1 //etc..
var icon = new GIcon();
icon.image = "/mapIcons/icon"+num+".png";
icon.iconSize = new GSize(20,32);
icon.shadowSize = new GSize(20, 34);
icon.iconAnchor = new GPoint(11, 15);
icon.infoWindowAnchor = new GPoint(11, 15);
icon.shadow = "";

Categories

Resources