Google map stops working after clicking and moving mouse - javascript

I have following code that has two buttons, one to show a map and the other to hide it and show a paragraph. The problem is that first time I open the page it shows the map but as soon as I try to move it to find the selected positions it stops showing the map.
Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-social/4.2.1/bootstrap-social.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
</head>
<body>
<div id="myDiv" class="col-md-4 hidden-xs"
style="padding-left: 7px; background-color: white;">
<div class="row"
style="margin-left: 30px; margin-top: 36px; background-color: white;">
<div id="hideMap" class="col-md-5" onClick="hideMap()">Hide</div>
<div id="showMap" class="col-md-5" onClick="populateMap()">Show</div>
</div>
<div id="myMap" style="width: 380px; height: 400px"></div>
<div id="para"><p>This is it</p></div>
</div>
<script>
function hideMap() {
$("#myMap").hide();
$("#para").show();
}
function populateMap() {
$("#para").hide();
$("#myMap").show();
}
var map;
var markers = [];
var pinColor = "FE7569";
function pinImage(imagenum) {
return image = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld="
+ imagenum + "|" + pinColor);
}
function initialize() {
var centreLoc = new google.maps.LatLng(37.9908372,23.7383394);
var mapOptions = {
zoom : 13,
center : centreLoc,
disableDefaultUI : true,
mapTypeControlOptions : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('myMap'),
mapOptions);
hideMap();
var results = [ [ 'Pos1', 37.9908372,23.7383394 ],
[ 'Pos2', 37.89,23.7383394 ] ];
processResults(results);
}
function processResults(results) {
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
markers = [];
$("#marker-container").empty();
for (i = 0; i < results.length; i++) {
var place = results[i][0];
var placeLoc = new google.maps.LatLng(results[i][2], results[i][3]);
// Create a marker for each place.
var marker = new google.maps.Marker({
map : map,
title : place,
position : placeLoc,
icon : pinImage(i + 1)
});
markers.push(marker);
var description = $("<div class='marker-description'><image class='marker' src='" + marker.icon.url + "'></image><span class='place'>"
+ place + "</span>");
$("#marker-container").append(description);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>
Before (Once the demo is loaded)
After (Try to find an address on the map)

You need to trigger the 'resize' event on the map after it is displayed, then set the center once it has a size:
function populateMap() {
$("#para").hide();
$("#myMap").show();
google.maps.event.trigger(map,'resize');
map.setCenter(centreLoc);
}
updated fiddle
code snippet (removed signed_in=true, doesn't play well in SO code snippets):
function hideMap() {
$("#myMap").hide();
$("#para").show();
}
function populateMap() {
$("#para").hide();
$("#myMap").show();
google.maps.event.trigger(map,'resize');
map.setCenter(centreLoc);
}
var map;
var centreLoc;
var markers = [];
var pinColor = "FE7569";
function pinImage(imagenum) {
return image = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld="
+ imagenum + "|" + pinColor);
}
function initialize() {
centreLoc = new google.maps.LatLng(37.9908372,23.7383394);
var mapOptions = {
zoom : 13,
center : centreLoc,
disableDefaultUI : true,
mapTypeControlOptions : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('myMap'),
mapOptions);
hideMap();
var results = [ [ 'Pos1', 37.9908372,23.7383394 ],
[ 'Pos2', 37.89,23.7383394 ] ];
processResults(results);
}
function processResults(results) {
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
markers = [];
$("#marker-container").empty();
for (i = 0; i < results.length; i++) {
var place = results[i][0];
var placeLoc = new google.maps.LatLng(results[i][1], results[i][2]);
// Create a marker for each place.
var marker = new google.maps.Marker({
map : map,
title : place,
position : placeLoc,
icon : pinImage(i + 1)
});
markers.push(marker);
var description = $("<div class='marker-description'><image class='marker' src='" + marker.icon.url + "'></image><span class='place'>"
+ place + "</span>");
$("#marker-container").append(description);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places.js"></script>
<div id="myDiv" class="col-md-4 hidden-xs"
style="padding-left: 7px; background-color: white;">
<div class="row"
style="margin-left: 30px; margin-top: 36px; background-color: white;">
<div id="hideMap" class="col-md-5" onClick="hideMap()">Hide</div>
<div id="showMap" class="col-md-5" onClick="populateMap()">Show</div>
</div>
<div id="myMap" style="width: 380px; height: 400px"></div>
<div id="para"><p>This is it</p></div>
</div>

sorry for late response
if you mind please this one
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-social/4.2.1/bootstrap-social.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
</head>
<body>
<div id="myDiv" class="col-md-4 hidden-xs" style="padding-left: 7px; background-color: white;">
<div class="row" style="margin-left: 30px; margin-top: 36px; background-color: white;">
<div id="hideMap" class="col-md-5" onClick="hideMap()">Hide</div>
<div id="showMap" class="col-md-5" onClick="populateMap()">Show</div>
</div>
<div id="myMap" style="width: 380px; height: 400px;"></div>
<div id="para"><p>This is it</p></div>
</div>
<script>
function hideMap() {
$("#myMap").css('display', 'none');
$("#para").css('display', 'block');
}
function populateMap() {
$("#para").hide();
$("#myMap").show();
}
var map;
var markers = [];
var pinColor = "FE7569";
function pinImage(imagenum) {
return image = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" + imagenum + "|" + pinColor);
}
function initialize() {
var centreLoc = new google.maps.LatLng(37.9908372,23.7383394);
var mapOptions = {
zoom : 10,
center : centreLoc,
disableDefaultUI : true,
mapTypeControlOptions : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('myMap'), mapOptions);
var results = [ [ 'Pos1', 37.9908372,23.7383394 ], [ 'Pos2', 37.89,23.7383394 ] ];
processResults(results);
google.maps.event.addListenerOnce(map, 'idle', function(){
hideMap();
});
}
function processResults(results) {
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
markers = [];
$("#marker-container").empty();
for (i = 0; i < results.length; i++) {
var place = results[i][0];
var placeLoc = new google.maps.LatLng(results[i][1], results[i][2]);
// Create a marker for each place.
var marker = new google.maps.Marker({
map : map,
title : place,
position : placeLoc,
icon : pinImage(i + 1)
});
markers.push(marker);
var description = $("<div class='marker-description'><image class='marker' src='" + marker.icon.url + "'></image><span class='place'>" + place + "</span>");
$("#marker-container").append(description);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>
I put wrong style
<div id="myMap"></div>
<div id="para" style="width: 380px; height: 400px;"><p>This is it</p></div>
to this one
<div id="myMap" style="width: 380px; height: 400px;"></div>
<div id="para"><p>This is it</p></div>

Related

How do i fix a map api key? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
Hello I have created a map API key but it's not working can you help me how can i resolve it thanks
Here is website link: https://earnest-participati.000webhostapp.com/
"use strict";
var $placePicker = null,
$modal = null,
n=null,
btnClass="btn btn-secondary btn-sm",
placePickerMap = null,
marker = false,
service = null,
geocoder = null,
result = null;
$.fn.PlacePicker = function (t) {
n = {
key : null,
title : null,
center: {lat: -34.397, lng: 150.644},
zoom: 18,
success: function () {}
};
var params = $.extend(n, t);
$placePicker = this;
$(this).wrap( "<div></div>" );
$(this).closest("div").hover(function(){
var left = $(this).offset().left+$(this).width() - 40;
var top = $(this).offset().top+5;
var btn = $('<div class="placePickerUIButton" title="Pick location from map" style="position:absolute;top: '+top+'px;left: '+left+'px;z-index: 1000;"><div class="'+params.btnClass+'"><i class="fa fa-map"></i></div></div>');
$(this).append(btn);
btn.click(function(){
if($("body").find(".modal.placePicker").length==0){
$("body").append('<div class="modal fade in placePicker" role="dialog"><style>.pac-container{ z-index: 10000; }</style><div class="modal-dialog modal-lg" style="width: 90%;"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Place Picker</h4><button type="button" class="close" data-dismiss="modal">×</button></div><div class="modal-body" style="padding: 0px;"><div class="row"><div class="col-md-12" style="padding: 10px;position: absolute;z-index: 1;background: #fff;width: 30%;margin-left: 20px;margin-top: 4px;box-shadow: 0 2px 4px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12)!important;"><div class="input-group input-group-sm" style="width: 100%;"> <input type="text" class="form-control pull-right autocomplete" placeholder="Search here or pick a location on map" style="border: 1px solid #dddddd;" autocomplete="off"></div><div class="address_content" style="display: none"><div class="address" style="margin-top: 10px;display: block;padding: 9.5px;font-size: 13px;color: #333;background-color: #f5f5f5;border: 1px solid #ccc;border-radius: 4px;max-height: 50vh;overflow-x: hidden;overflow-y: scroll;text-align: left;"></div><div class="row"><div class="col-md-6"><div class="btn btn-sm btn-default" style="width: 100%;margin-top: 10px;margin-bottom: 10px;" data-dismiss="modal"><i class="fa fa-close"></i> Cancel</div></div><div class="col-md-6"><div class="btn btn-sm btn-success placePickerSubmit" style="width: 100%;margin-top: 10px;margin-bottom: 10px;"><i class="fa fa-check"></i> Select</div></div></div></div></div><div class="col-md-12"><div id="placePickerMap" style="height:calc( 80vh );width:100%"></div></div></div></div></div></div></div>');
}
result = null;
$modal = $(".placePicker");
$modal.modal("show");
$(".placePicker").find(".address").html("");
$(".placePicker").find(".address_content").hide();
$(".placePicker").find(".autocomplete").val("");
placePickerMap = null
marker = false;
if (!(typeof google === 'object' && typeof google.maps === 'object')) {
$.getScript('https://maps.googleapis.com/maps/api/js?key='+params.key+'&libraries=places', function() {
initPlacePickerMap(params)
});
} else{
initPlacePickerMap(params)
}
if(params.title!=null){
$modal.find(".modal-title").html(params.title);
}
$(".placePickerSubmit").click(function(){
var place = $(".placePicker").find(".autocomplete");
params.success(convertAddress(),place);
$modal.modal("hide")
});
$modal.on('hidden.bs.modal', function () {
$("body").find(".modal.placePicker").remove();
})
});
},
function(){
$("body").find(".placePickerUIButton").remove();
});
};
function initPlacePickerMap(params) {
service = new google.maps.Geocoder;
geocoder= new google.maps.Geocoder;
setTimeout(function() {
var loc = new google.maps.LatLng(params.center.lat, params.center.lng);
placePickerMap = new google.maps.Map(document.getElementById('placePickerMap'), {
center: loc,
zoom: params.zoom
});
service = new google.maps.places.PlacesService(placePickerMap);
var autocomplete = new google.maps.places.Autocomplete(document.getElementsByClassName("autocomplete")[0]);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (typeof place.address_components !== 'undefined') {
placePickerMap.panTo(place.geometry.location)
if(marker === false){
marker = new google.maps.Marker({
position: place.geometry.location,
map: placePickerMap,
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function(event){
markerLocation();
});
} else{
marker.setPosition(place.geometry.location);
}
markerLocation();
}
});
google.maps.event.addListener(placePickerMap, 'click', function(event) {
var clickedLocation = event.latLng;
if(marker === false){
marker = new google.maps.Marker({
position: clickedLocation,
map: placePickerMap,
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function(event){
markerLocation();
});
} else{
marker.setPosition(clickedLocation);
}
markerLocation();
});
}, 1000);
}
function markerLocation(){
var currentLocation = marker.getPosition();
geocoder.geocode({'location': currentLocation}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
result = results[0];
var cont = "<h6 style='font-weight:600;font-size: 16px;padding-bottom: 10px;'>"+result.formatted_address+"</h6>";
$(result.address_components).each(function(key,value){
cont += "<b>"+value.types.join(', ')+"</b> : "+value.long_name+"<br>";
});
$(".address").html(cont);
$(".address_content").show();
}
}
});
}
function convertAddress(){
var data=[];
data["country"]="";
data["administrative_area_level_2"]="";
data["postal_code"]="";
data["sublocality_level_1"]="";
data["sublocality_level_2"]="";
data["route"]="";
data["locality"]="";
data["formatted_address"] = result.formatted_address;
$(result.address_components).each(function(i,address){
$(address.types).each(function(j,type){
if(type=="country"){
data[type] = address.short_name;
}else{
data[type] = address.long_name;
}
});
});
return data;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="PlacePicker.png">
<title>Google Place Picker For Bootstrap Example</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.3.1/flatly/bootstrap.min.css">
<!-- Custom styles for this template -->
<link href="https://getbootstrap.com/docs/4.0/examples/sign-in/signin.css" rel="stylesheet">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="PlacePicker.js"></script>
</head>
<body class="text-center">
<form class="form-signin">
<img class="mb-4" src="PlacePicker.png" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal">Google Place Picker For Bootstrap Example</h1>
<div class="jquery-script-ads" style="margin:30px auto"><script type="text/javascript"><!--
google_ad_client = "ca-pub-2783044520727903";
/* jQuery_demo */
google_ad_slot = "2780937993";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="https://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<label for="inputEmail" class="sr-only">Address</label>
<input type="email" id="pickup_country" class="form-control" placeholder="Address" autofocus>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#pickup_country").PlacePicker({
btnClass:"btn btn-xs btn-default",
key:"AIzaSyCi5tx8le0PuE2P2vJnIdclkVeUL33WPjg",
center: {lat: 17.6868, lng: 83.2185},
success:function(data,address){
//data contains address elements and
//address conatins you searched text
//Your logic here
$("#pickup_country").val(data.formatted_address);
}
});
});
</script>
<style>
.form-signin {
width: 100%;
max-width: 630px;
padding: 15px;
margin: 0 auto;
}
</style>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-36251023-1']);
_gaq.push(['_setDomainName', 'jqueryscript.net']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
Below is the setting of the API key please check and let me know. If you can help me let me know. I'm waitunf for your response thanks
enter image description here

Google Maps Info Window calling from another API

I am trying to put info windows in for a Google Maps page. I am using an API to call data and also using the markerclusterer.js plugin. I've seen how to do it with with a JSON object or if the markers are within the JavaScript document but I don't understand how to apply it to calling from another API.
What am I doing wrong? Can you please explain?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>API Test</title>
<!--jQuery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"rel="stylesheet">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<!--CSS-->
<link href="style.css" rel="stylesheet" type="text/css">
<!--JavaScript-->
<script src="script.js" type="text/javascript">
</script>
<script src="markerclusterer.js" type="text/javascript">
</script>
</head>
<body>
<div class="container">
<br>
<div id="content">
<br>
<div id="googleMap"></div><br>
<footer id="footer">
<p>Footer</p>
</footer>
</div>
</div>
</body>
</html>
CSS:
#content {
box-shadow: 5px 5px 10px 5px black;
}
#googleMap {
height: 400px;
width: 100%;
border: 1px solid black;
}
JavaScript:
var map;
var MarkerClusterer;
var marker;
var mcOptions;
var markers = [];
$(document).ready(function() {
//Construct the query string
url ='https://opendata.howardcountymd.gov/resource/2rmt-d3f4.json?';
+ '$$app_token=3bEFB0E09z1w6zaJfAb6QqLsX';
function initialize() {
var mapProp = {
center: new google.maps.LatLng(39.287346, -76.964306),
zoom: 8,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById(
"googleMap"), mapProp);
var infowindow = new google.maps.InfoWindow({
content: "Hello World!"
});
google.maps.event.addListener(markers, 'click', function() {
console.log("hello world")
infowindow.open(map, Markers);
});
}
//google.maps.event.addDomListener(window, 'load', initialize);
initialize();
//Retrieve our data and plot it
$.getJSON(url, function(data, textstatus) {
$.each(data, function(i, entry) {
//Cluster Markers
for (var i = 0; i < 50; i++) {
var entryMarkers = entry[i];
var LatLng = new google.maps.LatLng(
parseFloat(entry.coordinates.latitude),
parseFloat(entry.coordinates.longitude)
);
}
var marker = new google.maps.Marker({
position: new google.maps.LatLng(
parseFloat(entry.coordinates
.latitude),
parseFloat(entry.coordinates
.longitude)),
map: map,
title: entry.file_name
});
markers.push(marker);
});
var markerCluster = new MarkerClusterer(map, markers);
});
//info windows
});
This is not valid:
google.maps.event.addListener(markers, 'click', function() {
console.log("hello world")
infowindow.open(map, Markers);
});
An event listener doesn't work on an array, needs to be added to each marker (that it applies to) individually.
You can use function closure to associate the infowindow to the marker (below example uses a createMarker function) and make the infowindow global. Note that you don't have to use function closure there are other ways to solve the issue. Below example puts the entry.file_name into the infowindow.
working fiddle
code snippet:
var map;
var MarkerClusterer;
var marker;
var mcOptions;
var markers = [];
var infowindow = new google.maps.InfoWindow({
content: "Hello World!"
});
$(document).ready(function() {
//Construct the query string
url = 'https://opendata.howardcountymd.gov/resource/2rmt-d3f4.json?' + '$$app_token=3bEFB0E09z1w6zaJfAb6QqLsX';
function initialize() {
var mapProp = {
center: new google.maps.LatLng(39.287346, -76.964306),
zoom: 8,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById(
"googleMap"), mapProp);
}
//google.maps.event.addDomListener(window, 'load', initialize);
initialize();
//Retrieve our data and plot it
$.getJSON(url, function(data, textstatus) {
$.each(data, function(i, entry) {
createMarker(entry);
});
var markerCluster = new MarkerClusterer(map, markers);
});
//info windows
});
function createMarker(entry) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(
parseFloat(entry.coordinates.latitude),
parseFloat(entry.coordinates.longitude)),
map: map,
title: entry.file_name
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
console.log("hello world");
infowindow.setContent(entry.file_name + "<br>" + marker.getPosition().toUrlValue(6));
infowindow.open(map, marker);
});
}
#input-area {
width: 100%;
border: 1px solid black;
}
#googleMap {
height: 400px;
width: 100%;
}
html,
body {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/googlemaps/v3-utility-library#07f15d84/markerclustererplus/src/markerclusterer.js"></script>
<!-- was https://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<div class="container">
<br>
<div id="content">
<br>
<div id="googleMap"></div>
<br>
<footer id="footer">
<p>Footer</p>
</footer>
</div>
</div>

how to fetch draggable marker latlng information

im making a solution that does the geocoding , i can get coords from adresse , and put a marker over this adresse , im trying to make this marker draggabele and everytime i change the marker position with the mouse , i must get the new cooords , can someone help me ?
edit : Solution with event.addlistner
this is my code (js + html )
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Geocoding service</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js? v=3.exp&signed_in=true"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(34.042145, -4.997128);
var mapOptions = {
zoom: 5,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
var lg;
var lat;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.setZoom(16);
var lat = results[0].geometry.location.lat();
document.getElementById('latitude').value = lat;
var lg = results[0].geometry.location.lng();
document.getElementById('longitude').value = lg;
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
draggable : true
});
}
else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<input id="address" type="textbox">
<input id="latitude" type="textbox" >
<input id="longitude" type="textbox" >
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas"></div>
</body>
</html>
Use Google Maps' getPosition function:
google.maps.event.addListener(marker,"dragend",function(){
document.getElementById("latitude").value=marker.getPosition().lat();
document.getElementById("longitude").value=marker.getPosition().lng();
});

How to add the svg code in google maps

I had a Blinking SVG code : http://jsfiddle.net/Muthukumaru/n4d80zLd/
I am trying to add this SVG code to the Google maps to the particular pointer so that that particular marker do blink
I am new to the Google maps API , How to add the SVG code to the Google maps Code :
This is the Code of the Google Maps :
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 1000px; height: 600px;"></div>
<script type="text/javascript">
var locations = [
['STHOWBGA01_ATIF_RNID_L015',24.31026,93.56268],
['GWTRGOK004_BILF_RNOD_L023',23.70692,91.27397],
['GWTRBLWBN1_BILF_RNOD_L038',24.0179,91.4529],
['SJOWKHL007_ATIF_RNOD_L012',25.35197,92.3723],
['TTINNMSAI4_VIOF_RNID_L011',27.66616,95.87926],
['SIMWUKHRL5_VIOF_RNID_L061',25.12267,94.36558],
['SDIMZLUKI3_BILF_RNOD_L035',25.63658,93.64943]
];
var lat_center = 24.31026,
long_center = 93.56268;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(lat_center, long_center),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i, text;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
text = locations[i][0];
if(locations[i][1] === lat_center && locations[i][2] === long_center) {
marker.setAnimation(google.maps.Animation.DROP);
marker.setIcon('https://maps.gstatic.com/intl/en_ALL/mapfiles/markers2/boost-marker-mapview.png');
}
google.maps.event.addListener(marker, 'mouseover', (function(marker, text) {
return function() {
infowindow.setContent(text);
infowindow.open(map, marker);
}
})(marker, text));
}
</script>
</body>
</html>
I had passed the particular center marker with link png image :
https://maps.gstatic.com/intl/en_ALL/mapfiles/markers2/boost-marker-mapview.png
Instead of png image link , I want to pass the SVG code from JSfiddle that I provided above:
can any one please help ,
Thanks
NEW CODE
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="css/search.css" />
<script type="text/javascript" src="js/jquery-1.7.1.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<style>
b{
color:red;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
<?php
include_once('connection.php');
$con=SQL_CONNECT();
$COMMAND="select unique(SITEID) from LATLONG";
$stid = oci_parse($con, $COMMAND);
$res=oci_execute($stid);
echo "var availableTags = [ ";
while ($row = oci_fetch_array($stid))
{
echo '"'.$row['SITEID'].'",';
}
echo "]";
oci_close($con);
?>
$('#site').autocomplete({
source: availableTags,
open: function (e, ui) {
var acData = $(this).data('autocomplete');
acData
.menu
.element
.find('a')
.each(function () {
var me = $(this);
var keywords = acData.term.split(' ').join('|');
me.html(me.text().replace(new RegExp("(" + keywords + ")", "gi"), '<b>$1</b>'));
});
}
});
// $( "#datepicker" ).datepicker();
$("#butn").click(function(){
var sitename=$("#site").val();
if(sitename.length==0)
{
alert("please enter text");
}
else
{
$("#fetch").load('one_marker.php',{sitename:sitename},function(res){
});
}
});
});
</script>
</head>
<body id='tableb'>
<table align="center" id='tables'>
<tr><td>ENTER TEXT: </td><td><input type="text" id="site" name="sitename" placeholder="Sitename"><div id="site_error"></div></td></tr>
<tr><td></td><td><input style="cursor:pointer" type="button" id="butn" value="submit"/></td></tr>
</table>
<div id="content" style="display:none;"></div>
<div id="fetch"></div>
</body>
</html>
The variable which i get the from the auto complete will pass through ajax call : blink_php.php
please check this page :
<?php
include_once('connection.php');
$conn=SQL_CONNECT();
$sitename=$_POST['sitename'];
$stid = oci_parse($conn, "SELECT * FROM latlong where SITEID like '%$sitename%'");
$res=oci_execute($stid);
while($data = oci_fetch_array($stid))
{ ?>
<div id="lati_center" style="display: none;">
<?php
echo htmlspecialchars($data['LAT']);
?>
</div>
<div id="longi_center" style="display: none;">
<?php
echo htmlspecialchars($data['LON']);
?>
</div>
<?php
}
oci_close($conn);
?>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<style>
#map {
margin:20px auto;
}
.reddot{
width:66px;
height:66px;
position:absolute
}
.locater{
position: absolute;
top: 18px;
left: 17px;
}
.mark{
fill: none;
stroke: #FF9100;
stroke-width: 1px;
cursor: pointer;
z-index: 1000;
}
</style>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
</head>
<body>
<div id="map" style="width: 1000px; height: 600px;"></div>
<script type="text/javascript">
var locations = [
<?php
include_once('connection.php');
$con=SQL_CONNECT();
$COMMAND="select * from LATLONG";
$stid = oci_parse($con, $COMMAND);
$res=oci_execute($stid);
$len = "select count(*) from latlong";
$len_c = oci_parse($con, $len);
$res_c=oci_execute($len_c);
$i=0;
while ($data = oci_fetch_array($stid))
{
if($i==$len - 1)
{
echo "['<b>".$data['SITEID']."</b><br>".$data['ADDRESS']."</br>',".$data['LAT'].",".$data['LON']."]" ;
}else{
echo "['<b>".$data['SITEID']."</b><br>".$data['ADDRESS']."</br>',".$data['LAT'].",".$data['LON']."]," ;
}
$i++;
}
oci_close($con);
?>
];
var div_lat = document.getElementById("lati_center");
var lat_center = div_lat.textContent;
var div_lon = document.getElementById("longi_center");
var long_center = div_lon.textContent;
alert(div_lat+","+div_lon)
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: new google.maps.LatLng(lat_center, long_center),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i, text;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
text = locations[i][0];
if(locations[i][1] === lat_center && locations[i][2] === long_center) {
// marker.setAnimation(google.maps.Animation.DROP);
marker.setIcon('https://maps.gstatic.com/intl/en_ALL/mapfiles/markers2/boost-marker-mapview.png');
map.Overlay= new google.maps.OverlayView();
map.Overlay.center_ = new google.maps.LatLng(lat_center, long_center);
map.Overlay.reddot_ = '<div id="reddot" class="reddot" style="position:relative;"><svg class="marker" height="66" width="66"><circle cy="33" cx="33" class="mark" r="25"><set id="show" attributeName="visibility" attributeType="CSS" to="visible" begin="0s; hide.end" dur="1s" fill="freeze"/><set id="hide" attributeName="visibility" attributeType="CSS" to="hidden" begin="show.end" dur="1s" fill="freeze"/></circle><img src="" class="locater"></svg></div>';
map.Overlay.draw = function () {
var pixelposition = this.getProjection().fromLatLngToDivPixel(this.center_);
jQuery('#reddot').css({top:(pixelposition.y-50), left:(pixelposition.x-33)});
};
map.Overlay.onAdd=function() {
var self=this;
jQuery(self.getPanes().markerLayer).append(self.reddot_);
};
map.Overlay.setMap(map);
}
google.maps.event.addListener(marker, 'mouseover', (function(marker, text) {
return function() {
infowindow.setContent(text);
infowindow.open(map, marker);
}
})(marker, text));
}
</script>
</body>
You can't use an SVG element as marker Icon. What you can do is mimic the behavior of google.maps.Marker using an google.maps.OverlayView element.
For example:
map.Overlay= new google.maps.OverlayView();
map.Overlay.center_ = new google.maps.LatLng(lat_center, long_center);
map.Overlay.reddot_ = '<div id="reddot" class="reddot" style="position:relative;"><svg class="marker" height="66" width="66"><circle cy="33" cx="33" class="mark" r="25"><set id="show" attributeName="visibility" attributeType="CSS" to="visible" begin="0s; hide.end" dur="1s" fill="freeze"/><set id="hide" attributeName="visibility" attributeType="CSS" to="hidden" begin="show.end" dur="1s" fill="freeze"/></circle><img src="http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png" class="locater"></svg></div>';
map.Overlay.draw = function () {
var pixelposition = this.getProjection().fromLatLngToDivPixel(this.center_);
jQuery('#reddot').css({top:(pixelposition.y-50), left:(pixelposition.x-33)});
};
map.Overlay.onAdd=function() {
var self=this;
jQuery(self.getPanes().markerLayer).append(self.reddot_);
};
map.Overlay.setMap(map);
See the working example at: http://bl.ocks.org/amenadiel/9e08b294d3bd7ce09220
(I used jQuery to append the SVG to the markerLayer pane, but you can do that with raw js too)

Google Version 3 Maps Geocoder, Get Coordinates of marker layer when clicking or dragging marker

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)

Categories

Resources